我正在开发一个机器人迷宫,机器人可以在不撞墙的情况下找到目标。作为一种“原路返回”方法,我需要机器人沿着与第一次遇到交叉路口时相反的方向行驶。这是我的代码:
最佳答案
这应该有效。我认为您可能忘记在执行初始 Junction currentJunction = junctionIterator.next();
后继续迭代列表,因此您从未真正遍历列表。另外,在使用 next()
之前,您可能需要始终检查 hasNext()
以防列表为空。
public int searchJunction(IRobot robot) {
boolean foundJunction = false;
Junction currentJunction = null;
//Iterate through list until the end, or until correct junction is found.
while (!foundJunction && junctionIterator.hasNext()) {
currentJunction = junctionIterator.next();
if ((((currentJunction.x)==(robot.getLocation().x))) && ((currentJunction.y)==(robot.getLocation().y))) {
foundJunction = true;
}
}
return currentJunction;
}
希望这能解决问题。
关于java - 如何使用迭代器返回 ArrayList 中的第一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27306892/