EDIT: Solved with simple change, solution at the bottom
I am supposed to make the program count how many times each value is rolled in a set of dice rolls and print that number out for each value. The array size is based on the ((number of dice * number of sides) + 1), but for some reason I still get this out of bounds exception with multiple different entries (for number of dice, sides, and rolls) I've tried. I don't see what could be throwing this exception.
import java.util.Scanner;
import java.lang.Math;
public class DiceRolls {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numRolls, numSides, numDice;
int outcome = 0;
/* prompt user for number of rolls */
System.out.print("How many sides on each die? ");
numSides = input.nextInt();
System.out.print("How many dice should be rolled? ");
numDice = input.nextInt();
System.out.print("How many rolls? ");
numRolls = input.nextInt();
input.close();
int arraySize = (numDice * numSides);
int[] outcomes = new int[arraySize + 1];
/* roll dice and add to outcomes */
for (int roll = 0; roll < numRolls; roll++) {
for (int dice = 0; dice < numDice; dice++) {
outcome += (int)(numSides * Math.random() + 1);
}
outcomes[outcome] += 1;
}
/* show counts of outcomes */
for (int i = numDice; i <= arraySize; i++) {
System.out.println(i + ": " + outcomes[i]);
}
}
}
Solution
I added the outcome = 0; line to reset the outcome with each new roll. Otherwise the outcome would keep accumulating and reach values higher than what is possible in a single roll.
/* roll dice and add to outcomes */
for (int roll = 0; roll < numRolls; roll++) {
outcome = 0; // <-----HERE
for (int dice = 0; dice < numDice; dice++) {
outcome += (int)(numSides * Math.random() + 1);
}
outcomes[outcome] += 1;
}