gpt4 book ai didi

java - 为什么我的掷骰子程序卡住了?

转载 作者:行者123 更新时间:2023-12-01 17:15:38 26 4
gpt4 key购买 nike

我的程序应该在数组中掷骰子 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");
}
}
}

最佳答案

数组的索引超出范围。在 Java 中,数组索引是从零开始的。您最多可获得 12 个位置,比高位高出 1 个位置:

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 种可能的和。

关于java - 为什么我的掷骰子程序卡住了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22311240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com