我的程序应该在一个数组中滚动一对骰子1000次,然后在最后吐出每个数字的频率。我以为我做得对,但它在运行时一直卡在++上。怎么了,怎么解决呢?
import java.util.Random;
public class dice {
public static void main (String[] args)
{
Random rand = new Random();
int[] counter = new int[12];
for (int i = 0 ; i<1000; i++)
{
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
int sum = roll1 + roll2;
counter[sum]++;
}
System.out.println("***********Results************");
for (int j=0; j<13; j++)
{
System.out.println(j+" occured "+counter[j]+" times");
}
}
}
答案 0 :(得分:5)
数组的索引超出范围。在Java中,数组索引是从零开始的。你最多获得12个,这是一个高位:
rand(6) + 1 // either: 1, 2, 3, 4, 5, 6
rand(6) + 1 // either: 1, 2, 3, 4, 5, 6
所以两者的总和将是以下之一:2,3,4,5,6,7,8,9,10,11,12。但是如果你创建的话,你只能从0到11(包括0和11)进行索引12个元素的数组。请注意,只有11种可能的总和。
答案 1 :(得分:0)
在while循环期间,如果您的总和得到值12(当两个骰子都滚动到6时发生) 通过访问count [] Array的方式,有效索引范围是0-11.So在这种情况下,您将获得异常。以下是对此的简单修复和有效的代码。
public class test {
public static void main (String[] args){
Random rand = new Random();
int[] counter = new int[13];
int roll1,roll2,sum;
for (int i = 0 ; i<1000; i++){
roll1 = rand.nextInt(6) + 1;
roll2 = rand.nextInt(6) + 1;
sum = roll1 + roll2;
counter[sum]++;
}
System.out.println("***********Results************");
for (int j=1; j<13; j++){
System.out.println(j+" occured "+counter[j]+" times");
}
}
}