kan*_*ast 0 java arrays random
我的程序应该在一个数组中滚动一对骰子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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
数组的索引超出范围.在Java中,数组索引是从零开始的.你最多得到12,这是一个高位:
rand(6) + 1 // either: 1, 2, 3, 4, 5, 6
rand(6) + 1 // either: 1, 2, 3, 4, 5, 6
Run Code Online (Sandbox Code Playgroud)
因此,两者的总和将是以下之一:2,3,4,5,6,7,8,9,10,11,12.但是,如果创建一个数组,则只能从0到11(包括0和11)进行索引. 12个要素.请注意,只有11种可能的总和.