Java 对于while循环中的每个循环,在while循环中的列表上使用remove
我的任务是创建一个比赛模拟器。我有8个对象存储在一个列表中。我需要查看其中一个对象何时越过终点线,并将其从列表中删除,然后将其放入另一个列表中。为此,我使用了一个For-each循环。我需要在每次执行一个步骤时执行这个检查,因此,foreachloop在while循环中。当每个人都越过终点线时,while循环将停止并结束比赛Java 对于while循环中的每个循环,在while循环中的列表上使用remove,java,Java,我的任务是创建一个比赛模拟器。我有8个对象存储在一个列表中。我需要查看其中一个对象何时越过终点线,并将其从列表中删除,然后将其放入另一个列表中。为此,我使用了一个For-each循环。我需要在每次执行一个步骤时执行这个检查,因此,foreachloop在while循环中。当每个人都越过终点线时,while循环将停止并结束比赛 while (lista.size()>0) { for (RaceTurtle raceTurtle : lista) {
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);
}
}
我曾尝试使用迭代器,但它只会抛出相同的错误。我也尝试过使用原始列表的副本,但这似乎不起作用,因为它在while循环中
如果有人能给我一个如何做到这一点的例子,我将不胜感激
再次尝试使用迭代器,这次成功了
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);
}
while(lista.size()>0){
for(Iterator Iterator=lista.Iterator();Iterator.hasNext();){
racetourl temp=iterator.next();
步骤()的温度;
if(temp.getX()>RaceWindow.X_END_POS){
优胜者。添加(临时);
iterator.remove();
}
}
w、 延迟(50);
}
< /代码> 如果您得到的是<代码> ARAYEXTEXOUTFOFFUNCTIONS 或类似的东西,考虑如果列表为空,请在<<代码> < <代码> > < <代码>循环>的同时中断<代码>。例如:
outer: // label the loop
while (lista.size()>0) {
for (RaceTurtle raceTurtle : lista) {
raceTurtle.raceStep();
if(raceTurtle.getX() > RaceWindow.X_END_POS) {
lista.remove(raceTurtle);
winners.add(raceTurtle);
}
if (lista.size()>0) {
break outer; // end the outer loop, preventing
// the possible iteration of nothing
}
w.delay(10);
}
}
如果你得到了<代码> ARAYEXIDEXOFFOUTHOMESSUVE 或类似的东西,考虑如果列表为空,请在<<代码> < <代码> > < < /Cult>循环>中打破<代码>。例如:
outer: // label the loop
while (lista.size()>0) {
for (RaceTurtle raceTurtle : lista) {
raceTurtle.raceStep();
if(raceTurtle.getX() > RaceWindow.X_END_POS) {
lista.remove(raceTurtle);
winners.add(raceTurtle);
}
if (lista.size()>0) {
break outer; // end the outer loop, preventing
// the possible iteration of nothing
}
w.delay(10);
}
}
可能重复使用了该示例,但效果很好,很奇怪,因为我之前使用了迭代器,但没有效果。可能重复使用了该示例,但效果很好,很奇怪,因为我之前使用了迭代器,但没有效果。Thx用于快速回答,但这为我解决了问题:while(lista.size()>0){for(Iterator Iterator=lista.Iterator();Iterator.hasNext()){raceturl temp=Iterator.next();temp.racestop();if(temp.getX()>raceswindow.X_END_POS){winners.add(temp);Iterator.remove();}}w.delay(50)}不可能在注释中格式化代码吗?在原始post.Thx中添加解决方案以获得快速答案,但这为我解决了问题:while(lista.size()>0){for(Iterator Iterator=lista.Iterator();Iterator.hasNext();){raceturl temp=Iterator.next();temp.racestop();if(temp.getX()>raceswindow.X_END_POS){winners.add(temp);iterator.remove();}}w.delay(50);}无法在注释中格式化代码吗?在原始帖子中添加解决方案。