java返回语句和中断在“While循环”中不起作用
我正在用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;
}
}
我读了其他一些关于类似问题的帖子。阅读一篇帖子(here)让我尝试在没有断点的情况下运行调试器。没有他们,我也会遇到同样的问题,但我不完全理解答案。我还尝试清除列表,使while条件无效,但它仍在继续
所以,我想我的问题有两个方面:
代码怎么能完全忽略break或return语句呢?如何使用断点获得一个结果,而不使用断点获得另一个结果
编辑:为了清晰起见,我添加了完整的while循环
# 1 楼答案
openList
正在被另一个线程写入/更改吗? 也许它不是一个线程安全列表,被另一个线程修改,而不是一个带有while循环的线程? 或者哪个线程将目标添加到列表中# 2 楼答案
代码不可能在返回语句之后运行。在返回语句之后,解释器退出该方法,我可以向您证明这一点
执行以下测试以添加系统。出来在return语句之前和之后printl无论运行代码时有断点还是没有断点,都会得到与return语句相同的结果。 编辑:我不确定这个测试是否可行。我记不起不可访问的代码是否被标记为警告或错误
break语句也是如此,在break语句之后,循环退出。但是,当你在一个循环中使用多个循环时,识别你退出的是哪个循环会让人困惑
如果你有手表,程序可以在调试模式下改变它的行为。如果手表上的方法发生了变化,那么你就会有不同的行为
例如:
如果在每个断点后都对getX()进行监视,调试器将调用getX(),y将递增1。你的程序会有不同于运行模式的行为
结论: