Let's say numberTracker = {1,15,6,8}
and numberString = {1,1,5,6,8}
. Each number in numberString
has its own tile.
I'm try to set for example 1,5 to the same tile color since it is equal to 15 in numberTracker
while tileIterator
contains the same length as numberString
.The code works perfectly and does what is is suppost to do. However I get java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
ListIterator < String > nmbTracker = numberTracker.listIterator();
ListIterator < Tile > tileIterator = tiles.listIterator();
Tile t;
int x = 0;
int y = 0;
while (nmbTracker.hasNext()) {
if (numberTracker.get(x).equals(numberString.get(y))) {
t = tileIterator.next();
t.setColor(tilePanel2.changeColour());
if (numberTracker.size() - 1 != x) {
x++;
}
if (numberString.size() - 1 != y) {
y++;
}
} else {
x++;
t = tileIterator.next();
t.setColor(tilePanel2.changeColour());
Color color = t.getColor();
t = tileIterator.next();
t.setColor(color);
y++;
y++;
}
repaint();
}
Well. That is what happens when you try to access index 5 in a list that has 4 elements in it. You are using the iterator's hasNext()
to see if there are any next
values available, yet you switch over to using get(x)
to access the list values. Pick one.
If you want to stick to the get(x)
, get rid of the hasNext()
and replace it with while(x<4 && y<5)
, so that the list accesses don't go out of bounds.
If you want the iterator
, instead of using get(x)
, use the iterator's next()
method.
Using both interchangeably is not good, at least in this case.