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);
// }
}
}
<小时/>
请参阅代码中的注释行://******** 这就是我遇到问题的地方。
for 循环应该输出滚动的总和。
它只是没有吐出正确的值。我只是好奇我哪里做错了?程序应该询问用户有多少卷。这将进入第一个 for 循环,第二个循环将掷骰子多次。
最佳答案
我认为您要做的就是按照指定的次数掷骰子,记录达到每个总数的频率,以便您可以在最后打印它们。试试这个:
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
关于java - 模具模拟器嵌套循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21448240/