I have an assignment where I'm to create a race simulator. I have 8 objects stored in a list. I need to see when one of the objects crosses the finish line and remove them from the list and put them in another list. For this, I'm using a for each loop. I need to perform this check each time one takes a step so, therefore, the foreachloop is inside a while loop. When everyone has crossed the finish line the while loop shall stop and end the race.
while (lista.size()>0) {
for (RaceTurtle raceTurtle : lista) {
raceTurtle.raceStep();
if(raceTurtle.getX() > RaceWindow.X_END_POS) {
lista.remove(raceTurtle);
winners.add(raceTurtle);
}
w.delay(10);
}
}
I have tried to use an iterator but it only throws me the same error. I have also tried to use a copy of the original list but that don't seem to work since it's inside a while loop.
Would apreciate if someone could give me an example of how this is to be done.
Tried again with iterator and this time it worked.
while (lista.size()>0) {
for (Iterator<RaceTurtle> iterator = lista.iterator(); iterator.hasNext();) {
RaceTurtle temp = iterator.next();
temp.raceStep();
if (temp.getX()> RaceWindow.X_END_POS) {
winners.add(temp);
iterator.remove();
}
}
w.delay(50);
}