我想将 5 个硬币作为一个小组抛 1024 次,然后数一下我得到了多少个反面。但是我收到 ArrayIndexOutOfBoundsException: 4 错误。
这是因为当第一个循环第一次运行时,第二个循环中的 j 没有被重置?如果是这样,那我该怎么做呢?
public class Q2 {
public static void main(String[] args) {
int totalTails, totalHeads;
int coin[];
coin = new int[4];
totalHeads = 0;
totalTails = 0;
for (int i = 0; i < 1024; i++) {
for (int j=0; i<5; j++){
coin[j] = 1 + (int) (Math.random() * (2 - 1 + 1));
if (coin[j] == 1) {
totalHeads++;
}
else {
totalTails++;
}
}
}
System.out.println("Number of tails were obtained = " + totalTails);
System.out.println("Number of heads were obtained = " + totalHeads);
}
}