[英]What's wrong with this for loop?
我正在為Android制作骰子游戲,並且我有一個循環,該循環用滾動“ j”滾動的編號填充數組。 像這樣
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]);
}
除了輸出(在日志文件中是這個)
Rolls[0] = 4
Rolls[0] = 2
Rolls[0] = 3
Rolls[0] = 6
Rolls[0] = 3
Rolls[0] = 4
當我將代碼更改為此
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]);
}
輸出正確
Rolls[0] = 4
Rolls[1] = 2
Rolls[2] = 3
Rolls[3] = 6
Rolls[4] = 3
Rolls[5] = 4
我一定在某處做蠢事。
該聲明:
for (int j : rolls)
遍歷rolls
的條目,而不是索引。 由於在Java中將數組初始化為0,因此6次迭代中的每一次j
的值為零。
for (int j : rolls) {
制作新數組時,卷數的值為0。
當您使用增強的for循環遍歷數組時,您沒有索引信息。
您可以確保迭代遍歷,因此,如果您自己跟蹤它,則可以這樣做。 但是如果您自己沒有做,那么您將沒有任何信息。
首先, j
將是每個數組元素的初始值。 在這種情況下,它們都是0,即默認值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.