Java error: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

5.2k views Asked by At

This is the error I am getting and I do not know why.

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

I thought it was the array list, but when I tried counter + 1 it didn't work either.

2

There are 2 answers

0
AngelTrs On

With the partial of code that you provided, it appears you only have one element in the diceData ArrayList. You need to have as many elements in the ArrayList as NUMBER_OF_SIDES for your loop to work without throwing the Exception.

You can check this by printing out diceData.size() to see if it is equal to or greater than NUMBER_OF_SIDES.

3
Ashish Patil On

your below code causes the problem--

   for (int col= 0; col < NUMBER_OF_SIDES; col++)
    { 
         int counter = 0;
        //Add each of the 6 letters to the die ArrayList representing 
        //the die letters by calling method addLetter in class Die 
        die.addLetter(diceData.get(counter).toString());
        counter++;
    }

The reason behind this is that,

your diceData arraylist reference is only instantiated but it didn't contained any value in it. i.e.diceData array list is empty.

So To avoid this situation do the following--

for (int col= 0; col < NUMBER_OF_SIDES; col++)
    { 
         int counter = 0;
        //Add each of the 6 letters to the die ArrayList representing 
        //the die letters by calling method addLetter in class Die 
        if(!diceData.isEmpty())
         {
        die.addLetter(diceData.get(counter).toString());
        counter++;
         }
        }

Also I am still not able to understand why you are always initializing and incrementing counter in above foor loop.? As I didn't see any use of that in your code.