當在其運行之間使用println
在同一控制檯上運行nextLine()
兩次時,我得到NoSuchElementException。掃描器的使用nextLine()拋出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)
爲什麼拋出的異常,以及如何我修復這個?