嵌套 For 循环不工作 Java
Nested For-Loop Not working Java
我不知道我是不是在这里,所以如果不是,请随时删除这个问题。
我想在用 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 来自德国
问题是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);
}
}
我不知道我是不是在这里,所以如果不是,请随时删除这个问题。
我想在用 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 来自德国
问题是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);
}
}