英文:
Rolling dice project: code gives out of bounds exception below 7 and fails to save the first "Die Number"
问题
我了解什么是越界异常,以及它是如何发生的,但我找不出为什么它会在我的代码中发生。另外,“Count for side 1”的输出始终为0。这是我的第一次发布,但我认为我发布得正确。
我认为问题出在这里。
System.out.println("现在投掷 " + chosenRollNumber + " 次。");
int[] count = new int[chosenRollNumber];
for (x = 0; x < chosenRollNumber; x++) {
dieNumber = RNG(randomNum, min, max);
System.out.println("骰子点数为 " + dieNumber);
count[dieNumber]++;
}
System.out.println("完成所有骰子的投掷");
for(x = 0; x < numberOfSides; x++) {
System.out.println("第 " + (x + 1) + " 面的计数为 " + count[x]);
}
while(true) {
英文:
I understand what out of bounds exception means, and how it happens, but I can't find out why it's happening in my code. Also, the output "Count for side 1" always states 0. This is my first post, but I think I am posting this right.
This is where I think the problem is.
System.out.println("Now rolling " + chosenRollNumber + " times. ");
int[] count = new int[chosenRollNumber];
for (x = 0; x < chosenRollNumber; x++) {
dieNumber = RNG(randomNum, min, max);
System.out.println("dieNumber " + dieNumber);
count[dieNumber]++;
}
System.out.println("Done rolling all dice");
for(x = 0; x < numberOfSides; x++) {
System.out.println("Count for side " + (x + 1) + " is " + count[x]); }
while(true) {
答案1
得分: 0
方法 RNG(randomNum, min, max)
预期返回范围在 [min...max]
(包括 min 和 max)之间的值,而作为 count
数组中索引的 dieNumber
需要在 [0; numberOfSides)
范围内,且满足以下关系 numberOfSides == max - min + 1
。
因此,需要进行修正以将 dieNumber
转换为有效的索引:
System.out.println("现在投掷 " + chosenRollNumber + " 次。");
int[] count = new int[numberOfSides];
for (x = 0; x < chosenRollNumber; x++) {
dieNumber = RNG(randomNum, min, max);
System.out.println("骰子点数 " + dieNumber);
int dieIndex = (dieNumber - min) % numberOfSides;
count[dieIndex]++;
}
英文:
Method RNG(randomNum, min, max)
is expected to return values in the range [min...max]
(inclusive), while dieNumber
as the index in count
array needs to be in the range [0; numberOfSides)
, and the following relation exists numberOfSides == max - min + 1
.
So, a correction is needed to transform dieNumber
into a valid index:
System.out.println("Now rolling " + chosenRollNumber + " times. ");
int[] count = new int[numberOfSides];
for (x = 0; x < chosenRollNumber; x++) {
dieNumber = RNG(randomNum, min, max);
System.out.println("dieNumber " + dieNumber);
int dieIndex = (dieNumber - min) % numberOfSides;
count[dieIndex]++;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论