import java.util.Scanner;
public class DiceSimulator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many dice do you want to roll: ");
int amountOfDie = input.nextInt();
System.out.println("");
// declare diceArray
Die[] diceArray = new Die[amountOfDie];
// create a new Die for each reference
int maxRoll = 0;
for (int i = 0; i < diceArray.length; i++) {
System.out.print("How many sides on die number " + (i + 1) + "" + ": ");
int numSides = input.nextInt();
diceArray[i] = new Die(numSides);
int minRoll = amountOfDie;
maxRoll += numSides;
}
int minRoll = amountOfDie;
// int[] sumArray = new int[maxRoll + 1];//to store sum
System.out.println("");
System.out.print("How many times do you want to roll: ");
int numRol = input.nextInt();
System.out.println("\nResults");
// ******** right here is where I'm having the issue.
for (int i = 0; i < numRol; i++) {
diceArray[i].roll();
// System.out.println(diceArray[i]);
int sum = 0;
for (int f = 0; f < numRol; f++) {
sum += diceArray[f].roll();
int[] sumArray = new int[maxRoll + 1];
sumArray[sum]++;
System.out.print("\t" + sum);
}
}
// for(Die d: diceArray){
// System.out.println(d);
// }
}
}
请参阅代码中的注释行:// ******** right here is where I'm having the issue.
for循环应该吐出卷的总和 它只是没有吐出正确的价值观。我只是好奇我哪里出错了?该程序应询问用户有多少卷。这将进入第一个for循环,第二个将多次掷骰子。
答案 0 :(得分:1)
我认为你要做的就是将这些骰子滚动这么多次,跟踪每个总数达到的频率,这样你就可以在最后打印它们。试试这个:
int[] sumArray = new int[maxRoll];
for (int i = 0; i < numRol; i++) {
int sum = 0;
for (Die d : diceArray) {
int roll = d.roll();
sum += roll;
System.out.print("\t" + roll);
}
System.out.println("\t:\t" + sum);
sumArray[sum-1]++;
}
for (int i = 0; i < sumArray.length; i++){
System.out.printf("%d: %d Rolls\n", i+1, sumArray[i]);
}
你可以看到它正常工作here。你最基本的错误是:
如果使用此算法将两个六面骰子滚动10次,您将获得:
Results
4 3 : 7
5 5 : 10
2 2 : 4
6 5 : 11
1 1 : 2
6 5 : 11
6 5 : 11
1 2 : 3
2 1 : 3
3 5 : 8
1: 0 Rolls
2: 1 Rolls
3: 2 Rolls
4: 1 Rolls
5: 0 Rolls
6: 0 Rolls
7: 1 Rolls
8: 1 Rolls
9: 0 Rolls
10: 1 Rolls
11: 3 Rolls
12: 0 Rolls
答案 1 :(得分:0)
您的行如下所示:
diceArray[i].roll();
问题是diceArray只是你拥有的骰子数量很大。但是你试图将它与卷数的索引一起使用。这可能会导致ArrayOutOfBoundsException。