11684
11684

Reputation: 7507

Strange loop output - Java

Wy are these loops:

while (x <= gridWidth) {
            while (y <= gridHeight) {
                System.out.println("X: " + x + ", Y: " + y);
                y++;
            }
            x++;
        }

outputting this:

    X: 0, Y: 0
    X: 0, Y: 1
    X: 0, Y: 2
    X: 0, Y: 3
    X: 0, Y: 4
    X: 0, Y: 5
    X: 0, Y: 6
    X: 0, Y: 7
    X: 0, Y: 8
    X: 0, Y: 9
    X: 0, Y: 10
    X: 0, Y: 11
    X: 0, Y: 12
    X: 0, Y: 13
    X: 0, Y: 14
    X: 0, Y: 15
    X: 0, Y: 16
    X: 0, Y: 17
    X: 0, Y: 18
    X: 0, Y: 19
    X: 0, Y: 20
    X: 0, Y: 21
    X: 0, Y: 22
    X: 0, Y: 23
    X: 0, Y: 24
    X: 0, Y: 25
    X: 0, Y: 26
    X: 0, Y: 27
    X: 0, Y: 28
    X: 0, Y: 29
    X: 0, Y: 30
    X: 0, Y: 31
    X: 0, Y: 32
    X: 0, Y: 33
    X: 0, Y: 34
    X: 0, Y: 35
    X: 0, Y: 36
    X: 0, Y: 37
    X: 0, Y: 38
    X: 0, Y: 39
    X: 0, Y: 40
    X: 0, Y: 41
    X: 0, Y: 42
    X: 0, Y: 43
    X: 0, Y: 44
    X: 0, Y: 45
    X: 0, Y: 46
    X: 0, Y: 47
    X: 0, Y: 48
    X: 0, Y: 49
    X: 0, Y: 50

?

I am very sure that gridWidth = 50, because I printed it.

Upvotes: 1

Views: 161

Answers (5)

Andrea Parodi
Andrea Parodi

Reputation: 5614

As Joshua Bloch suggests in it's book Effective Java, use the for construct instead of the while whenever you can. Is less error prone, more concise, and in effect it would have probably prevented your error.

for (int x=0;x <= gridWidth;x++)
    for (int y=0;y <= gridHeight;y++)
        System.out.println("X: " + x + ", Y: " + y);

Upvotes: 2

Dave L.
Dave L.

Reputation: 9791

final int gridWidth = 50, gridHeight = 50;

for(int x = 0; x <= gridWidth; x++)
  for(int y = 0; y <= gridHeight; y++)
    System.out.println("X: " + x + ", Y: " + y);

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

int y=0,x=0;
while (x <= gridWidth) {
   while (y <= gridHeight) {
    System.out.println("X: " + x + ", Y: " + y);
    y++;
  }
x++;
y=0;
}

Upvotes: 0

bluesman
bluesman

Reputation: 2260

You aren't re initializing y with each loop

    while (x <= gridWidth) {
        y = 0;
        while (y <= gridHeight) {
            System.out.println("X: " + x + ", Y: " + y);
            y++;
        }
        x++;
    }

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You need to reset y back to zero before the nested loop starts. Otherwise, the outer loop will execute 50 times, but the last 49 times the inner loop will not execute at all, because y is already above gridHeight.

Upvotes: 9

Related Questions