简体   繁体   中英

What's wrong with this for loop?

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:

 for (int j : rolls) 

Iterates over the entries in rolls , not the indices. Since arrays are initialized to 0 in Java, the value j is zero for each of the 6 iterations.

for (int j : rolls) {

When you make a new array, the value of the number in rolls is 0.

When you use an enhanced for loop over an array you have NO index information.

You ARE guaranteed to iterate in over, so if you keep track of it yourself, you can do that. But without doing it yourself you have no information about it.

In the first, j will be the initial value of each array element. In this case, they are all 0, the default.

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