I’m making a dice game for android and i have this loop that fills an array with the numbered rolled at roll “j”. It went like this
int[] rolls = new int[6];
for (int j : rolls) {
rolls[j] = (int) (Math.random() * 5);
rolls[j]++;
Log.i(getClass().getName(), "Rolls[" + j + "] = " + rolls[j]);
}
Except the output (in the logfile is this)
Rolls[0] = 4
Rolls[0] = 2
Rolls[0] = 3
Rolls[0] = 6
Rolls[0] = 3
Rolls[0] = 4
And when i change the code to this
int[] rolls = new int[6];
for (int j = 0; j < rolls.length ; j++) {
rolls[j] = (int) (Math.random() * 5);
rolls[j]++;
Log.i(getClass().getName(), "Rolls[" + j + "] = " + rolls[j]);
}
the output is correct
Rolls[0] = 4
Rolls[1] = 2
Rolls[2] = 3
Rolls[3] = 6
Rolls[4] = 3
Rolls[5] = 4
I must be doing something stupid somewhere.
The statement:
Iterates over the entries in
rolls, not the indices. Since arrays are initialized to 0 in Java, the valuejis zero for each of the 6 iterations.