简体   繁体   English

嵌套的For-Loop不能使用Java

[英]Nested For-Loop Not working Java

I don't know if I'm right here, so if not, please feel free to delete this question. 我不知道我是不是就在这里,所以如果没有,请随时删除这个问题。

I want to iterate over a 2-Dimensional Plane of Blocks in a Minecraft Plugin written in Java. 我想在用Java编写的Minecraft插件中迭代块的二维平面。 Therefore I want to go through every Block in every Row. 因此,我想要遍历每一行中的每个街区。 The following is my code. 以下是我的代码。 (Obviously shortened) (显然缩短了)

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);
        }
    }
  }
}

But this only outputs the following: 但这只输出以下内容:

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

So what's the Problem? 所以有什么问题? Please feel free to try it on your own. 请随意尝试。 Thanks in advance! 提前致谢!

Greetings, 问候,

Max from Germany Max来自德国

The problem is that currentZ is initialized in the wrong place. 问题是currentZ在错误的地方初始化。 It should be initialized before the inner loop: 它应该在内循环之前初始化:

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);
    }
}

You would have avoided this error if you used the for loops as they were meant to be used : 如果您使用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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM