简体   繁体   中英

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. 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

The problem is that currentZ is initialized in the wrong place. 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 (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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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