使用Scanner的nextLine()方法会抛出NoSuchElementException异常。

3

当在两次使用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)

为什么会抛出异常,以及如何修复它?

3个回答

3
当您编写以下代码时,即关闭底层流System.in

您正在关闭底层流System.in,当您编写:

final Scanner in = new Scanner(System.in);
final String input = in.nextLine();
in.close();

你不需要那样做。移除close调用。你也可以考虑在整个过程中使用同一个 Scanner (也许是传递它,或者把它放在静态字段中)。


3
Scanner 类的一个问题在于调用 Scanner.close() 会同时关闭它正在读取的输入流。在这种情况下,它会关闭 System.in,一旦被关闭就无法重新打开。
如果可能的话,应该在类级别上声明您的 Scanner 并保持其打开状态。从 System.in 中读取的类通常不需要关闭。

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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接