嵌套的For-Loop不能使用Java

时间:2015-02-08 13:25:51

标签: java for-loop nested-loops minecraft

我不知道我是不是就在这里,所以如果没有,请随时删除这个问题。

我想在用Java编写的Minecraft插件中迭代块的二维平面。因此,我想要遍历每一行中的每个街区。以下是我的代码。 (显然缩短了)

package mainiterator;

public class MainIterator {

  public static void main(String[] args) {
    int currentX = -2;
    int currentZ = -2;
    for (; currentX < 2; currentX++) {
        for (; currentZ < 2; currentZ++) {
            //The following should normally be outputted 4*4 Times. (16)
            System.out.println("currentX:" + currentX + " currentZ:" + currentZ);
        }
    }
  }
}

但这仅输出以下内容:

currentX:-2 currentZ:-2
currentX:-2 currentZ:-1
currentX:-2 currentZ:0
currentX:-2 currentZ:1

那么问题是什么? 请随意尝试。提前谢谢!

问候,

来自德国的Max

1 个答案:

答案 0 :(得分:9)

问题是currentZ在错误的位置初始化。它应该在内循环之前初始化:

int currentX = -2;
for (; currentX < 2; currentX++) {
    int currentZ = -2;
    for (; currentZ < 2; currentZ++) {
        //The following should normally be outputted 4*4 Times. (16)
        System.out.println("currentX:" + currentX + " currentZ:" + currentZ);
    }
}

如果您使用for循环,则可以避免此错误:

for (int currentX = -2; currentX < 2; currentX++) {
    for (int currentZ = -2; currentZ < 2; currentZ++) {
        //The following should normally be outputted 4*4 Times. (16)
        System.out.println("currentX:" + currentX + " currentZ:" + currentZ);
    }
}