![](/img/trans.png)
[英]I can't understand the output of the code fragment. can some one explane it to me please?
[英]could some one explane this java loop for me
import java.util.Random;
class arel {
public static void main(String args[]){
Random rand = new Random();
int[] number = new int[7];
for(int roll = 1; roll < 100; roll++){
++number[1+rand.nextInt(6)];
}
System.out.println("Index\tValue");
for(int count = 1; count<number.length; count++){
System.out.println(count+"\t"+number[count]);
}
}
}
++number[1+rand.nextInt(6)];
該行是否意味着為每個索引插入隨機數?
++number[1 + rand.Next(6)];
類似於:
// get a random number between 1 and 6
int index = 1 + rand.nextInt(6);
// increase the element of the array at the given random index by 1
number[index] = number[index] + 1;
行++number[1+rand.nextInt(6)];
利用Java中的數組是0初始化和操作順序的事實。
生成1到6之間的隨機數。 基於隨機值遞增陣列number
的適當索引。 此操作多次循環。 最后,使用第二個循環打印出每個值的打印次數。
但是,此代碼從不使用number
數組的0索引。 實際上,它是浪費的空間,必須(和)在第二個循環中占用。
它正在做什么:
作者忽略零指數的事實有點嗅覺。
int[] number = new int[7]; // first index=0, last=6.
// After creation all elements are 0
在for循環中,你調用99行: ++number[1+rand.nextInt(6)];
++number[index]; // it's the same: number[index]=number[index]+1
rand.nextInt(n)
方法返回0..n-1之間的隨機整數。 的javadoc
在您的示例中,您向該隨機數添加一個,因此您在以下之間有一個隨機數:1..6
現在你可以理解所有的代碼,所以我相信你會知道它的作用。 請注意,您的數組的第一個索引為零,並且永遠不會更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.