package HomePlace;
import java.util.Scanner;
import java.util.Random;
public class DiceRolls {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many sides? ");
int Usides = input.nextInt();
System.out.print("How many dice to roll? ");
int Udices = input.nextInt();
System.out.print("How many rolls? ");
int Urolls = input.nextInt();
int[] outcomes = new int[Usides * Udices];
for (int rolls = 0; rolls < Urolls; rolls++) {
outcomes[sum(Usides, Udices)] += 1;
}
for (int i = Udices; i <= Urolls; i++) {
System.out.println(i + ": " + outcomes[i-1]);
}
}
public static int sum(int Us, int Ud) {
int dicesum = 0;
for (int i = 0; i <= Ud; i++) {
int dots = (int) (Math.random() * Us + 1);
dicesum += dots;
}
return dicesum;
}
}
This is a code where the User declares how many sides (of the dice), how many dice (number of dice), and how many rolls that the User would perform. For example, if the User choose the dice would have 3 sides, the variable would be 1~3 and If the User inputs 5 dices and 5 rolls, it would be throwing 5 (3sided) dice for 5 times. My output should display the possible sums and how many times that sum came out. For example, If I throw 2 of 6 sided dice 2 times, the output should count the number of sums that came out from each roll.
Now my problem is I get the error
How many sides? 3
How many dice to roll? 4
How many rolls? 5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 12 out of bounds for length 12
at HomePlace.DiceRolls.main(DiceRolls.java:21)
and if I put large input
How many sides? 123
How many dice to roll? 123
How many rolls? 123
123: 0
I only get this output. where I want the output would be
How many sides on the die? 7
How many dice to roll? 5
How many rolls? 100
5: 0
6: 0
7: 0
8: 0
9: 1
10: 1
11: 2
12: 0
13: 2
14: 5
15: 9
16: 5
17: 4
18: 2
19: 9
20: 6
21: 8
22: 11
23: 10
24: 7
25: 6
26: 5
27: 2
28: 1
29: 3
30: 1
31: 0
32: 0
33: 0
34: 0
35: 0
Obviously I did something wrong in that code.. can i get help?