简体   繁体   English

Java:使用Scanner时总是收到NoSuchElementException

[英]Java: always receive NoSuchElementException when use Scanner

I have this simple code: 我有这个简单的代码:

    public class Example {
       public Example() {
          Scanner scanner = new Scanner(System.in);
          int row = scanner.nextInt();   // exception at this line
          scanner.close();
       }

    public static void main(String[] args) {
        Example ex1 = new Example();   // this line successfully operate
        Example ex2 = new Example();   // exception : no such element exception at above line
    }
  }

I don't know why I always receive this Exception, when code run to ex2. 当代码运行到ex2时,我不知道为什么我总是收到此异常。

You Should add if(Scanner.hasNext()) before invoking scanner.nextInt(); 你应该在调用scanner.nextInt()之前添加if(Scanner.hasNext()); You have the exception because no int found to be read. 您有异常,因为没有找到int被读取。

The problem is because you close the Scanner which in turn closes the underlying InputStream (in this case stdin). 问题是因为您关闭了Scanner ,而Scanner又关闭了底层的InputStream (在本例中为stdin)。 When you try to use stdin in again the Scanner is unable to retrieve any data because stdin has been closed. 当您尝试再次使用stdin时, Scanner无法检索任何数据,因为stdin已关闭。

If running directly from the commandlne then the correct way to provide access to stdin is to use the Console class. 如果直接从commandlne运行,那么提供stdin访问权限的正确方法是使用Console类。 The console class provides a Reader wrapped around stdin that has a no-op close method. 控制台类提供了一个包含stdin的Reader,它具有no-op close方法。 eg. 例如。

public class Example {
   public Example() {
      Scanner scanner = new Scanner(System.console().reader()); 
      // note change on above line
      int row = scanner.nextInt();
      scanner.close();
   }
}

Note, if you access stdin other than via the Console class then you'll likely cause problems for yourself. 请注意,如果您通过Console类访问stdin,那么您可能会自己造成问题。 And if you invoke your java program other than directly from the command line then you will not get access to the console. 如果您直接从命令行调用您的java程序,那么您将无法访问控制台。 For instance, the following will invokations cause problems. 例如,以下将调用引起问题。

echo 2 3 | java Example

or 要么

Process p = new ProcessBuilder("java", "Example").start();
// write data to process

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM