Reputation: 41
I want to make a simple program that rolls a dice 1000 times and counts the amount of times each number 1-6 appears. It works fine but there is an error at the end.Why is it happening?
public class diceRollerCounter {
public static void main(String[] args) {
int dice [] = new int[7];
for(int x = 0 ; x <1000; x++ ) {
++dice [(int)(Math.random()*6+1)];
}
System.out.println("Number Frequency" );
for(int index = 0; 1 < dice.length ; index++) {
System.out.println(index + " " + dice[index]);
}
}
}
OUTPUT:
Number Frequency
0 0
1 170
2 143
3 188
4 165
5 173
6 161
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at diceRollerCounter.main(diceRollerCounter.java:20)
Upvotes: 0
Views: 4145
Reputation: 178253
Your for
loop condition tests if 1
is less than dice.length
, and it's always true
. But you keep incrementing index
until it's off the end of the array.
Instead test if index
is less than dice.length
.
Incidentally, you may want to initialize index
to 1
, so that you skip the output of the number 0
appearing with a frequency of 0
.
Upvotes: 3