我正在使用Netbeans在Java中編寫一個簡短的算法。Return Statement和Break在「While Loop」中不起作用
我遇到的問題是代碼忽略了while循環中的return語句。我也嘗試了一個休息聲明,它也忽略了這一點。但是,關於整個事情的奇怪的部分是,當我用斷點運行程序時,它應該停止(當它看到一個特定的值時)。如果我沒有斷點運行它,它會經過那個點。
這裏有點代碼:
while (!openList.isEmpty()) {
// 1. Remove the best node from OPEN, call it current
int bestValue = Integer.MAX_VALUE;
for (BestFirstNode inOpen : openList) {
if ((inOpen.x == current.x) && (inOpen.y == current.y)) {
//skip this node
}
// 2.If one of the values in openList is the goal state, return the goal value
if (inOpen.value < bestValue) {
if (inOpen.value == goal) {
System.out.println("GOAL!");
openList.clear();
return goal;
}
//else sent thevalue if the new current nodes
bestValue = inOpen.value;
current = inOpen;
//set the new x and y values that will be used to check
//for successors
x = inOpen.x;
y = inOpen.y;
}
}
//print the current node and its coordinates
System.out.println("Current: " + current.value);
System.out.println("x: " + current.x + " y: " + current.y + "\n-------------");
//remove current from the openList so it can't be used again
openList.remove(current);
//3. Create current's successors.
Set<BestFirstNode> successors = new HashSet();
int min = 0;
int max = 2;
//get the top successor
if ((x <= max) && (x >= min) && (y - 1 <= max) && (y - 1 >= min)) {
successors.add(grid[x][y - 1]);
}
//get the bottom successor
if (x <= max && x >= min && y + 1 <= max && y + 1 >= min) {
successors.add(grid[x][y + 1]);
}
//get the left successor
if (x - 1 <= max && x - 1 >= min && y <= max && y >= min) {
successors.add(grid[x - 1][y]);
}
//get the right successor
if (x + 1 <= max && x + 1 >= min && y <= max && y >= min) {
successors.add(grid[x + 1][y]);
}
//remove the parent node from the successors list
Set<BestFirstNode> successorsFinal = new HashSet<>();
for (BestFirstNode successor : successors) {
if (successor != current.parent) {
successorsFinal.add(successor);
}
}
//4. Evaluate each successor, add it to OPEN, and record its parent.
for (BestFirstNode successor : successorsFinal) {
openList.add(successor);
successor.parent = current;
}
}
我閱讀了有關類似問題的其他幾個帖子。讀一篇文章(here)讓我嘗試運行沒有斷點的調試器。沒有他們,我會遇到同樣的問題,但我不完全明白答案。我也嘗試清除列表,以便條件無效,但它仍然繼續。
所以,我想我的問題是雙重的:
代碼如何完全忽略中斷或返回語句?你怎麼能得到一個結果使用斷點和另一個沒有他們?
編輯:我補充完整而清晰
觀察你的變量與調試,你會發現結果。 – Rugal
@Rugal我不知道我明白這將如何幫助。當我在調試時,我得到了預期的結果。 – JustBlossom
你的'inOpen'對象來自哪裏?如果你基本上遍歷你的'openList',你可能更適合用for each-loop這個目的。如果沒有,請在調試時監視您的'inOpen.value'變量。你的代碼是否通過了第二個if-query? –