【发布时间】:2015-07-06 12:13:12
【问题描述】:
一段时间以来,我一直试图找出错误在此代码中的位置,但我就是想不通。该程序正在滚动一个 6 面骰子 300 次,然后输出每个数字滚动的次数。但由于某种原因,它不是滚动 300 次,而是滚动了 320 次。我看不出for循环有什么问题,所以我真的很茫然。
public static void dieRoll(){
int[] roll = new int [300];
int[] count = new int[] {1,2,3,4,5,6};
for(int i = 1; i<300; i++){
roll[i] = (int) Math.ceil( (int) (Math.random()*6)+1 );
// roll[i] = (int) Math.ceil(roll[i]);
// System.out.println(roll[i]);
if(roll[i]==1){
count[0]++;
}
else if(roll[i]==2){
count[1]++;
}
else if(roll[i]==3){
count[2]++;
}
else if(roll[i]==4){
count[3]++;
}
else if(roll[i]==5){
count[4]++;
}
else if(roll[i]==6){
count[5]++;
}
// System.out.println(roll[i]);
}//i loop
System.out.println("The die landed on 1 " + count[0] + " times.");
System.out.println("The die landed on 2 " + count[1] + " times.");
System.out.println("The die landed on 3 " + count[2] + " times.");
System.out.println("The die landed on 4 " + count[3] + " times.");
System.out.println("The die landed on 5 " + count[4] + " times.");
System.out.println("The die landed on 6 " + count[5] + " times.");
System.out.println("The die was rolled this many times: " + (count[0]+count[1]+count[2]+count[3]+count[4]+count[5]));
}//dieRoll()
如果有人能指出错误可能在哪里表现出来,那就太棒了。谢谢。
【问题讨论】:
-
如果您在进入循环之前 执行最后一次 println,您将看到问题所在。您的
count数组以非零值开头。