[英]Basic Java Array and For Loop
I am taking a Java class and have read the same explanation over and over and I just want to make sure I am understanding it correctly. 我正在学习Java课程并且一遍又一遍地阅读相同的解释,我只是想确保我正确地理解它。
The example in the class they provide is a dice rolling game and they want to see the frequency of rolls per number. 他们提供的课程中的例子是骰子滚动游戏,他们希望看到每个数字的滚动频率。
The code snippet that I am uncertain on is this: 我不确定的代码片段是这样的:
for(int roll = 1; roll < 1000; roll++){
++freq[1+rand.nextInt(6)];
}
I understand this part: 1+rand.nextInt(6)
我理解这一部分:
1+rand.nextInt(6)
But I don't understand this part: ++freq
and how it tallys the results 但我不明白这一部分:
++freq
以及它如何计算结果
I am understanding this as (with the example I rolled a 4): 我理解这一点(以我的例子为例4):
for(int roll = 1; roll < 1000; roll++){
++freq[4];
//all indexes in freq are == 0 to start
//freq[4] is index 4 in the array. It was 0 but is now == to 1
//freq[0], freq[1], freq[2], freq[3], freq[5], and freq[6] are all still == to 0
}
for(int roll = 1; roll < 1000; roll++){
++freq[6];
//freq[6] is index 6 in the array. It was 0 but is now == to 1
//freq[0], freq[1], freq[2], freq[3], and freq[5] are all still == to 0
//freq[4] and freq[6] are both == to 1
}
Is this correct? 这个对吗?
int[] freq = new int[7];
for(int roll = 1; roll < 1000; roll++){
++freq[1+rand.nextInt(6)];
}
In the above code rand.nextInt(6)
returns a value from 0 to 5 which is used to access the relevant integer value of the array freq
在上面的代码中,
rand.nextInt(6)
返回一个从0到5的值,用于访问数组freq
的相关整数值
++freq
part increases the accessed integer value by 1. ++freq
part将访问的整数值增加1。
Example: if rand.nextInt(6)
returns 2
, 示例:如果
rand.nextInt(6)
返回2
,
freq[1 + 2] = freq[1 + 2] + 1;
However, from 1 + rand.nextInt(6)
, 0 is never produced. 但是,从
1 + rand.nextInt(6)
,0永远不会产生。 Therefore, the first element of freq
array should be ignored. 因此,应该忽略
freq
数组的第一个元素。
freq[n]
will give you the frequency of the nth
face. freq[n]
会给你nth
面的频率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.