简体   繁体   English

这个for循环有什么问题?

[英]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". 我正在为Android制作骰子游戏,并且我有一个循环,该循环用滚动“ 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. 遍历rolls的条目,而不是索引。 Since arrays are initialized to 0 in Java, the value j is zero for each of the 6 iterations. 由于在Java中将数组初始化为0,因此6次迭代中的每一次j的值为零。

for (int j : rolls) {

When you make a new array, the value of the number in rolls is 0. 制作新数组时,卷数的值为0。

When you use an enhanced for loop over an array you have NO index information. 当您使用增强的for循环遍历数组时,您没有索引信息。

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. 首先, j将是每个数组元素的初始值。 In this case, they are all 0, the default. 在这种情况下,它们都是0,即默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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