I understand what out of bounds exception means, and how it happens, but I can’t find out why it’s happening in my code. Also, the output “Count for side 1” always states 0. This is my first post, but I think I am posting this right.
This is where I think the problem is.
System.out.println("Now rolling " + chosenRollNumber + " times. "); int[] count = new int[chosenRollNumber]; for (x = 0; x < chosenRollNumber; x++) { dieNumber = RNG(randomNum, min, max); System.out.println("dieNumber " + dieNumber); count[dieNumber]++; } System.out.println("Done rolling all dice"); for(x = 0; x < numberOfSides; x++) { System.out.println("Count for side " + (x + 1) + " is " + count[x]); } while(true) {
Advertisement
Answer
Method RNG(randomNum, min, max)
is expected to return values in the range [min...max]
(inclusive), while dieNumber
as the index in count
array needs to be in the range [0; numberOfSides)
, and the following relation exists numberOfSides == max - min + 1
.
So, a correction is needed to transform dieNumber
into a valid index:
System.out.println("Now rolling " + chosenRollNumber + " times. "); int[] count = new int[numberOfSides]; for (x = 0; x < chosenRollNumber; x++) { dieNumber = RNG(randomNum, min, max); System.out.println("dieNumber " + dieNumber); int dieIndex = (dieNumber - min) % numberOfSides; count[dieIndex]++; }