我已经为家庭作业返回了一个骰子卷,并且在计算每个号码滚动的次数方面遇到了麻烦。我返回滚动到main并将其添加到一个数组但它只是不计算。我已经尝试过人们所说的并做出一些改变而且更接近但仍然没有得到正确的反击。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many times should I roll the dice? ");
int userIn = input.nextInt();
int[] rolls = new int[13];
rolls[simDiceRoll(userIn)]++;
for(int i = 2; i < rolls.length; i++) {
System.out.println(i + " was rolled " + simDiceRoll(userIn) + " times");
}
}
public static int simDiceRoll (int userNum) {
int roll1 = (int) (Math.random() * 6) + 1;
int roll2 = (int) (Math.random() * 6) + 1;
int rolls = roll1 + roll2;
return rolls;
}
输出
How many times should I roll the dice? 10000
2 was rolled 10 times
3 was rolled 10 times
4 was rolled 7 times
5 was rolled 5 times
6 was rolled 8 times
7 was rolled 12 times
8 was rolled 9 times
9 was rolled 6 times
10 was rolled 10 times
11 was rolled 6 times
12 was rolled 6 times
答案 0 :(得分:0)
您确实拥有用户输入,可以提供您想要制作的骰子数量。在for循环中使用该数字,只需创建一个整数大小为14的数组。在每个循环中,您只需向数组[数字滚动]添加1,最后循环遍历此数组中的每个项目,例如代码中的for和打印值。
我希望这对你有帮助。
答案 1 :(得分:0)
首先,您的代码中没有任何数组。你每次得到“7”结果的原因是因为“int roll”被定义为之前循环,而不是循环内部。
尝试用'simDiceRoll(userIn)'替换'roll':
System.out.println(i + " was rolled " + simDiceRoll(userIn) + " times");