2015-03-13 63 views
2

当在其运行之间使用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) 

为什么抛出的异常,以及如何我修复这个?

回答

3

有关Scanner类的一件事是,在扫描仪上调用Scanner.close()也会关闭它正在读取的输入流。在这种情况下,关闭System.in,关闭后无法重新打开。

如果可能,您应该在课堂级声明Scanner,并将其保持打开状态。阅读System.in的课程通常不需要关闭。

3

您关闭底层流,System.in,当你写:

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

您不必这样做。拨打close。你也可以考虑使用相同的扫描仪(可能传递它,或者把它放在一个静态字段中)。

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. 
相关问题