在同一控制台上运行 nextLine()
两次,同时在两次运行之间使用 println
时,我得到 NoSuchElementException。
首先我运行这个:
public void ask() {
System.out.print(title);
answer = getAnswer();
}
private String getAnswer() {
System.out.println("Before first nextLine()");
final Scanner in = new Scanner(System.in);
final String input = in.nextLine();
in.close();
System.out.println("After first nextLine()");
return input;
}
然后我运行这个:
@Override
public void ask() {
System.out.println(title);
int index = 0;
for (Option o : options)
System.out.println(index++ + " : " + o.getTitle());
System.out.println("Before second nextLine()");
final Scanner in = new Scanner(System.in);
String answer = in.nextLine();
in.close();
System.out.println("After second nextLine()");
this.answer = options.get(Integer.parseInt(answer)).getTitle();
}
这是输出:
How old are you?Before first nextLine()
32
Exception in thread "main" java.util.NoSuchElementException: No line found
After first nextLine()
at java.util.Scanner.nextLine(Scanner.java:1540)
Sex
at SingleChoise.ask(SingleChoise.java:25)
0 : Male
at Main.main(Main.java:17)
1 : Female
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Before second nextLine()
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
为什么会抛出异常,我该如何解决?
最佳答案
关于 Scanner
类的一件事是调用 Scanner.close()在扫描器上也会关闭它正在读取的输入流。在这种情况下,这就是关闭 System.in
,一旦关闭就无法重新打开。
如果可能,您应该在类级别声明您的Scanner
,并保持打开状态。从 System.in
读取的类通常不需要关闭。
关于java - 使用扫描器 nextLine() 会抛出 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29035072/