Reputation: 138
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
Upvotes: 3
Views: 2395
Reputation: 393936
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);
}
}
Upvotes: 9