使用Dijkstra,您可以使用最终条件
while(!q.isEmpty()){
//Some code
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您知道结束节点,是否无法将结束条件更改为
while(!q.peek().equals(endNode){
//Some code
}
Run Code Online (Sandbox Code Playgroud)
我见过的Dijkstra的每个实现都使用前面的版本,但是当你知道结束节点时,后者会更快.或者这不是Dijkstra了吗?
我打印不同的选项,用户输入一个数字来选择正确的选项.它第一次工作,但是当选择一个选项时,它会根据所选选项打印不同的选项.当用户尝试从第二个打印列表中选择一个选项时,程序会陷入无限循环.
protected int getIntegerInput(Scanner scan) {
while (! scan.hasNextInt())
;
return scan.nextInt();
}
protected <T> int getChoice(String description, List<T> list) {
printPosibilities(description, list);
while (true) {
try (Scanner scan = new Scanner(System.in)) {
int choice = getIntegerInput(scan) - 1;
scan.close();
if (isValidChoice(choice, list)) {
if (choice == list.size()) {
System.out.println("Canceled.");
return CANCEL;
}
return choice;
} else
throw new IllegalArgumentException();
} catch (InputMismatchException | IllegalArgumentException e) {
printInvalidChoice();
}
}
}
Run Code Online (Sandbox Code Playgroud)
它在getIntegerInput()中陷入困境.在打印可能的选项时调用getChoice().
编辑 我修好了.您需要删除该尝试,因为它会自动关闭扫描仪.而while循环中的scan.next().