在同一个控制台上运行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)
为什么抛出异常以及如何解决这个问题?
答案 0 :(得分:3)
当你写下来时,你正在关闭基础流System.in
:
final Scanner in = new Scanner(System.in);
final String input = in.nextLine();
in.close();
你不需要这样做。删除close
电话。您也可以考虑在整个过程中使用相同的扫描仪(或者将其传递给静态字段)。
答案 1 :(得分:3)
关于Scanner
类的一件事是,在扫描程序上调用Scanner.close()也将关闭它正在读取的输入流。在这种情况下,关闭System.in
,一旦关闭就无法重新开启。
如果可能,您应该在班级声明Scanner
,并将其保持打开状态。从System.in
读取的课程通常不需要关闭。
答案 2 :(得分:0)
来自javadoc:
* When searching, if no line terminator is found, then a large amount of
* input will be cached. If no line at all can be found, a
* NoSuchElementException will be thrown out.