So I’m getting an index out of bounds exception on some code i’m writing. What I don’t understand is that I know for a fact that the index element I’m trying to work with exists.
Here’s the code:
I have a constructor for an array list
public StixBoard(int number)
{
stixGame = new ArrayList<Integer>(number);
for (int i = 0; i < number; i++)
{
stixGame.add(i);
}
}
This block generates a random variable 1-3
public int computeMove()
{
int numberOfStix = (int) (3.0 * Math.random()) + 1;
return numberOfStix;
}
Really straight forward, now here I have a method that takes the parameter supplied and attempts to remove those number of elements from the array list. As you can see, the parameter must be between 1 and 3, and it must be less than or equal to the size of the array list. Otherwise, the user is prompted to enter another number
public boolean takeStix(int number)
{
boolean logicVar = false;
placeHolder = stixGame.size();
if ((number >= 1 && number <= 3) && number <= placeHolder)
{
for (int i = 0; i < number; i++)
{
stixGame.remove(i);
logicVar = true;
}
} else if (number > 3 || number > placeHolder)
{
do
{
System.out
.println("Please enter a different number, less than or equal to three.");
Scanner numberScan = new Scanner(System.in);
number = numberScan.nextInt();
} while (number > 3 || number > placeHolder);
}
return logicVar;
}
So as this program runs, the computeMove() method generates a random int (assuming the role of a computerized player) and attempts to translate that value to the number of indexes to be removed from the array list.
This ultimately brings me to this:
How many stix on the table? 4
|||||||||| 4 stix on the table
It's the computer's turn!
The computer chose 3
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.remove(ArrayList.java:387)
at StixBoard.takeStix(StixBoard.java:38)
at StixGame.main(StixGame.java:55)
So as you can see, the array list is of size 4, but when the computer rolls a 3, (which should leave me with 1), I am left with this error. How does my array list go from being of size 4 indexes to size 2?
You iterate through your list, from beginning to end, and remove an element at each step. This makes all the elements in the list shift to the left.
First iteration: i = 0
Second iteration: i = 1
Third iteration: i = 2
Iterate from the end to the beginning instead. That willmake it correct, and faster since the list won’t have to copy all the elements from right to left.