![](/img/trans.png)
[英]How can I determine the type of object an ArrayList iterator will return next?
[英]How to return the first result in an ArrayList using iterator
我在一個機器人迷宮上工作,在該迷宮中機器人可以找到目標而不會撞到牆壁。 作為一種“回溯”方法,我需要機器人沿與剛遇到交叉路口時相反的方向前進。 這是我的代碼:
這應該工作。 我認為您在執行了初始Junction currentJunction = junctionIterator.next();
后可能已經忘記繼續遍歷列表了Junction currentJunction = junctionIterator.next();
,因此您從未真正瀏覽過該列表。 此外,你可能要經常檢查hasNext()
使用前next()
的情況下,有一個空的列表。
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;
}
希望這可以清除一切。
在while循環中,您遇到的麻煩似乎沒有解決到最后一個結點。這是設計使然嗎? 還是應該
while (junctionIterator.hasNext()) {
if ((((currentJunction.x)==(robot.getLocation().x))) && ((currentJunction.y)==(robot.getLocation().y)))
break;
currentJunction = junctionIterator.next();
}
讓我知道這是否有幫助或我是否誤解了您的要求
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.