我想知道,当我从教程中学习Java时,有一个程序可以掷骰子1000次并打印其频率。
import java.util.Random;
public class RollDicewitharray {
public static void main(String[] args) {
Random r=new Random();
int arr[]= new int[7];
System.out.println("diceNo.\tFrequency");
for (int roll = 1; roll < 1000; roll++) {
++arr[1+r.nextInt(6)]; /* this line */
}
for (int i = 1; i < arr.length; i++) {
System.out.println(i+"\t"+arr[i]);
}
}
最佳答案
总而言之,该程序模拟滚动六面骰子 1000 次,并记录每个滚动数字的出现。
public static void main(String[] args) {
Random r=new Random();
int arr[]= new int[7]; //Craete an array with 7 int elements
System.out.println("diceNo.\tFrequency");
for(int roll=1;roll<1000;roll++){ //Loop 1000 times
++arr[1+r.nextInt(6)]; //Randomly pick arr[1] to
} //arr[6] and plus one to it
for(int i=1;i<arr.length;i++){
System.out.println(i+"\t"+arr[i]); //Print occurrence of 1-6
}
}
破坏以下代码:
++arr[1+r.nextInt(6)]; //r.nextInt(6) will be evaluated first:
<小时/>
r.nextInt(6)
返回 (0-5)
的随机值,因此您有:
++arr[1+(random 0 to 5)]; //+1 will be evaluated next:
因此,您将生成一个随机值 1-6
。接下来将 1 添加到数组中:
++arr[random 1 to 6]; //+1 to arr[1] or arr[2] or arr[3] or arr[4] or arr[5] or arr[6]
现在可以解释为:
arr[1] +=1; //or
arr[2] +=1; //or
arr[3] +=1; //or
arr[4] +=1; //or
arr[5] +=1; //or
arr[6] +=1;
<小时/>
因此,运行程序后,如果您的数组如下所示:
[0] [1] [2] [3] [4] [5] [6] Array index
+---+---+---+---+---+---+---+
| 0 |175|170|165|170|165|175| <-- arr
+---+---+---+---+---+---+---+
It means 1 was rolled 175 times,
2 was rolled 170 times,
3 was rolled 165 times,
and so on..
关于java - `++arr[1+r.nextInt(6)];` 这行代码是做什么的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35627203/