【发布时间】:2019-01-31 18:31:22
【问题描述】:
我正在学习 Java 课程并且一遍又一遍地阅读相同的解释,我只是想确保我正确理解它。
他们提供的课程中的示例是掷骰子游戏,他们想查看每个数字的掷骰频率。
我不确定的代码 sn-p 是这样的:
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
}
这对吗?
【问题讨论】:
-
++freq[4]是freq[4] = freq[4] + 1的缩写 -
为了记录,
++freq[1+rand.nextInt(6)];是相当不清楚的代码。除非你是在 2 英寸的屏幕上开发,或者因为编写更多代码行而受到惩罚,否则将其写为变量int roll = 1 + rand.nextInt(6);和增量++freq[roll];会更清晰。
标签: java arrays for-loop random