我一遍又一遍地提示用户输入,直到用户类型退出,在这种情况下,数据对象将被设置为 null 并且它将离开循环。在大多数情况下,此代码有效,但有时我会在行上得到NoSuchElementExceptionreader = new Scanner(System.in);
: 。这往往发生在几个循环之后,而不是第一次。如果我在 while 循环的范围内另外声明 reader 变量,那么它将在第二个循环中失败。
主要工作(有时抛出异常)
int level = 1;
Scanner reader;
String selection = null;
while (true) {
if (data.done) {
level--;
}
data.done = false;
System.out.println(getSubmenu(level, data));
reader = new Scanner(System.in);
if (level <6) {
selection = reader.nextLine();
} else {
level = 4;
}
if (validSelection(selection)) {
level = getLevel(level, selection);
data = getData(level, data, selection);
} else {
System.out.println("Invalid entry");
}
if (data == null) {
System.out.println("Level "+ level + "selection " + selection);
break; // exit command was typed
}
}
reader.close();
备用(在第二个循环中抛出异常)
int level = 1;
String selection = null;
while (true) {
if (data.done) {
level--;
}
data.done = false;
System.out.println(getSubmenu(level, data));
Scanner reader = new Scanner(System.in);
if (level <6) {
selection = reader.nextLine();
} else {
level = 4;
}
if (validSelection(selection)) {
level = getLevel(level, selection);
data = getData(level, data, selection);
} else {
System.out.println("Invalid entry");
}
if (data == null) {
System.out.println("Level "+ level + "selection " + selection);
break; // exit command was typed
}
reader.close();
}
堆栈跟踪
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at org.functional.utils.Menu.run(ServerScripts.java:61)
at org.functional.utils.ServerScripts.main(ServerScripts.java:18)
我错过了什么?