[英]Basic Java Array and For Loop
我正在学习Java课程并且一遍又一遍地阅读相同的解释,我只是想确保我正确地理解它。
他们提供的课程中的例子是骰子滚动游戏,他们希望看到每个数字的滚动频率。
我不确定的代码片段是这样的:
for(int roll = 1; roll < 1000; roll++){
++freq[1+rand.nextInt(6)];
}
我理解这一部分: 1+rand.nextInt(6)
但我不明白这一部分: ++freq
以及它如何计算结果
我理解这一点(以我的例子为例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
}
这个对吗?
int[] freq = new int[7];
for(int roll = 1; roll < 1000; roll++){
++freq[1+rand.nextInt(6)];
}
在上面的代码中, rand.nextInt(6)
返回一个从0到5的值,用于访问数组freq
的相关整数值
++freq
part将访问的整数值增加1。
示例:如果rand.nextInt(6)
返回2
,
freq[1 + 2] = freq[1 + 2] + 1;
但是,从1 + rand.nextInt(6)
,0永远不会产生。 因此,应该忽略freq
数组的第一个元素。
freq[n]
会给你nth
面的频率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.