-6
Random random = new Random();
int freq[] = new int[7]; // 0,1,2,3,4,5,6

for(int i=1; i<=1000; i++)
{
    ++freq[random.nextInt(6) + 1];
}

System.out.println("Face\tFrequency");

**for(int z=1; z<=freq.length; z++)**
{
    System.out.println(z + "\t" + freq[z]);
}

I am getting:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 

in highlighted part for some reason and I am watching thenewboston channel it is exactly the same as his and

I am using Intelij IDEA newest version. The thing is that if I put 6 then it works for no problem. What is the issue here ?

SOLVED sorry for wasting time I put <= instead of < , tnx everyone for help

1 Answers1

3

Array indices are 0 based (and the last index is length - 1).

Your loop should be :

for(int z=0; z<freq.length; z++)
{
    System.out.println(z+1 + "\t" + freq[z]);
}

You'll also have to change

++freq[random.nextInt(6) + 1];

to

++freq[random.nextInt(6)];

assuming the length of freq is 6.

Eran
  • 387,369
  • 54
  • 702
  • 768