【发布时间】:2018-04-12 08:51:55
【问题描述】:
我是迭代器的新手,不确定自己做错了什么。在我的项目中,车站有有乘客的汽车,汽车也可以有乘客。我的目标是检查汽车是否已到达其目标车站,如果没有,则将其从当前车站移除并将其添加到下一个车站,从而将其移动到下一个车站。
Iterator<Station> stations = allStations.iterator();
while(stations.hasNext())
{
Station currentStation = (Station)stations.next();
ArrayList<Car> currentStationCars = currentStation.getCarList();
Iterator cars = currentStationCars.iterator();
Car currentCar = (Car)cars.next();
while(cars.hasNext())
{
最初,我在这里声明了 currentCar,但这导致了 NoSuchElement 异常——我猜是因为我在每次迭代时都不断向前移动光标。不确定,我一个小时前才知道这个。现在,这段代码导致了一个无限循环。
//original position of currentCar declaration
int stepper = 0;
if(currentCar.getCurrentLocation() < currentCar.getDestination())
{
stepper = 1;
}
else if(currentCar.getCurrentLocation() > currentCar.getDestination())
{
stepper = -1;
}
while(stepper != 0)
{
currentCar.setCurrentLocation(currentCar.getCurrentLocation() + stepper);
currentStation.removeCar(currentCar);
if(currentCar.getCurrentLocation() < currentCar.getDestination())
{
stepper = 1;
}
else if(currentCar.getCurrentLocation() > currentCar.getDestination())
{
stepper = -1;
}
else {
stepper = 0;
}
}
}
【问题讨论】:
-
你永远不会在 while 循环中调用
currentCar.next()和stations.next() -
使用调试器找出发生了什么
标签: java iterator infinite-loop nosuchelementexception