1

这些循环是什么:

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

输出这个:

    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

?

我很确定gridWidth = 50,因为我打印了它。

4

5 回答 5

9

y在嵌套循环开始之前,您需要重置为零。否则,外层循环将执行 50 次,但内层循环的最后 49 次根本不会执行,因为y已经在gridHeight.

于 2012-05-03T18:20:18.983 回答
2

正如Joshua Bloch在其著作Effective Java中所建议的那样,尽可能使用 for 构造而不是 while。更不容易出错,更简洁,实际上它可能会阻止你的错误。

for (int x=0;x <= gridWidth;x++)
    for (int y=0;y <= gridHeight;y++)
        System.out.println("X: " + x + ", Y: " + y);
于 2012-05-03T18:34:27.553 回答
0

您没有在每个循环中重新初始化 y

    while (x <= gridWidth) {
        y = 0;
        while (y <= gridHeight) {
            System.out.println("X: " + x + ", Y: " + y);
            y++;
        }
        x++;
    }
于 2012-05-03T18:27:09.333 回答
0
int y=0,x=0;
while (x <= gridWidth) {
   while (y <= gridHeight) {
    System.out.println("X: " + x + ", Y: " + y);
    y++;
  }
x++;
y=0;
}
于 2012-05-03T18:27:11.520 回答
0
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);
于 2012-05-03T18:31:34.763 回答