gpt4 book ai didi

java - 使用迭代器的无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:06 29 4
gpt4 key购买 nike

我是迭代器新手,不确定我做错了什么。在我的项目中,车站有汽车,汽车有乘客,汽车也可以有乘客。我的目标是检查一辆车是否已到达目标车站,如果没有,则通过将其从当前车站中删除并将其添加到下一个车站来将其移动到下一个车站。

        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;
}
}
}

最佳答案

您仅在循环之前推进迭代器一次。这意味着如果列表为空,您将得到一个异常(因为您在检查 cars.hasNext() 之前调用了 cars.next()),如果列表至少有一个元素,您将得到一个无限循环,因为您不会前进到循环内的下一个 Car

您应该只在循环内推进迭代器:

while (cars.hasNext())
{
Car currentCar = (Car)cars.next();
....
}

请注意,如果您使用泛型类型,则可以避免转换:

Iterator<Car> cars = currentStationCars.iterator();
...
while(cars.hasNext())
{
Car currentCar = cars.next();
....
}

关于java - 使用迭代器的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49792101/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com