I am a Java beginner. I am writing a method that should iterate through every possible value of a byte array, but the limit for each byte number in the array is 13. So, I am using nested loops. Here is the code I currently have:
public static void iterateThroughMoves() {
byte[] moveSet = {0, 0, 0, 0};
while(moveSet[0] < 14) {
while(moveSet[1] < 14) {
while(moveSet[2] < 14) {
while(moveSet[3] < 14) {
System.out.println(Arrays.toString(moveSet));
moveSet[3] ++;
}
moveSet[2] ++;
}
moveSet[1] ++;
}
moveSet[0] ++;
}
}
For some reason, when I run this method, it prints this one the console:
[0, 0, 0, 0]
[0, 0, 0, 1]
[0, 0, 0, 2]
[0, 0, 0, 3]
[0, 0, 0, 4]
[0, 0, 0, 5]
[0, 0, 0, 6]
[0, 0, 0, 7]
[0, 0, 0, 8]
[0, 0, 0, 9]
[0, 0, 0, 10]
[0, 0, 0, 11]
[0, 0, 0, 12]
[0, 0, 0, 13]
Process finished with exit code 0
Shouldn’t it print every possible value of the array? And why is it breaking out of the loop? The first while loop won’t break unless the value of the first index of the byte array is greater than 13, and, as we can see in the console output, it never ends up being greater than 13.
I honestly don’t know what to try. I’ve been looking a lot at the code, and I can’t figure out what is wrong. As I previously mentioned, I am a beginner, so please don’t get mad at me if this is an incredibly simple problem with a stupidly simple solution.
>Solution :
The issue is that you are not resetting the values of moveSet[1], moveSet[2], and moveSet[3] after the outer loop increments moveSet[0].
In order to resolve this, you should reset the values of moveSet[1], moveSet[2], and moveSet[3] back to 0 in the innermost loop (when moveSet[3] increments to 14), and reset the values of moveSet[2] and moveSet[3] back to 0 in the second innermost loop (when moveSet[2] increments to 14), and finally reset the value of moveSet[1] back to 0 in the third innermost loop (when moveSet[1] increments to 14).
public static void iterateThroughMoves() {
byte[] moveSet = {0, 0, 0, 0};
while(moveSet[0] < 14) {
while(moveSet[1] < 14) {
while(moveSet[2] < 14) {
while(moveSet[3] < 14) {
System.out.println(Arrays.toString(moveSet));
moveSet[3] ++;
}
moveSet[2] ++;
moveSet[3] = 0;
}
moveSet[1] ++;
moveSet[2] = 0;
}
moveSet[0] ++;
moveSet[1] = 0;
}
}