我正在使用Netbeans用Java编写一个简短的算法。
我遇到的问题是,代码忽略了while循环中的return语句。我还尝试了一个break语句,但它也忽略了这一点。
然而,整件事的奇怪之处在于,当我用断点运行程序时,它会在应该停止的时候(当它看到某个值时)停止。如果我在没有断点的情况下运行它,它就会超过那个点。
这里有一点代码:
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;
}
}
我读过其他一些关于类似问题的帖子。读到一篇文章(这里),我尝试在没有断点的情况下运行调试器。如果没有它们,我会遇到同样的问题,但我并不完全理解答案。我还试着清除列表,这样while条件就无效了,但它仍然在继续。
所以,我想我的问题有两个:
代码怎么能完全忽略break或return语句呢?如何使用断点获得一个结果,而不使用断点获得另一个结果?
编辑:为了清晰起见,我添加了完整的while循环
openList
是否正在被另一个线程写入/更改?也许这不是一个线程安全列表被另一个线程修改,而不是被带有while循环的线程修改?或者哪个线程将目标添加到列表中?
您的代码不可能在返回语句之后运行。在返回语句之后,解释器退出方法,我可以向您证明这一点。
执行以下测试,在return语句之前和之后添加System.out.printl,无论您运行带有断点还是不带有断点的代码,都会得到与return语句相同的结果。编辑:我不确定这个测试是否可行。我记不清无法访问的代码是否标记为警告或错误
break语句也是如此,在break语句之后,循环将退出。但是,当你在彼此内部使用多个循环时,识别你正在退出的循环会很混乱。
如果你有手表,程序可以在调试模式下改变它的行为。如果你监视的方法改变了一些事情,你就会有不同的行为。
示例:
int getX(){
y++;
return x;
}
如果在每个断点后监视getX(),调试器将调用getX((),y将递增1。您的程序将具有与运行模式不同的行为。
结论:
- 程序永远不会忽略return或break语句,请证明我错了
- 断点刷新你的手表,手表调用他们正在观看的方法。如果这些方法改变了值,那么你就会有不同的行为