简体   繁体   中英

Scanner class' hasNext() on infinite loop

I'm trying to write code that uses the Scanner class to get input from the user. But hasNext(), hasNextInt(), and hasNextLine() all run into infinite loops every time.

public static void getInput(ArrayList<Double> arr){

       Scanner input = new Scanner(System.in);
       String data = "";
       String init;
       while(input.hasNextLine()){
           init = input.nextLine();
           data += init;
       }
       .
       .
       .
   }

Invoking hasNextLine() on a Scanner Object will return false if and only if the source is closed. This can occur by invoking close() on the InputStream , if an IOException occurs when the Scanner attempts to read bytes from the source or if the end of the stream has been reached ( EOF ). While an InputStream of a File will be closed when you reach the end and receive this marker, reading from System.in will block until data is available or an exception is thrown.

On Unix the EOF marker is usually provided by Ctrl-D while on Windows it is usually Ctrl-Z . If you are using an IDE you may find these to be different; For example the Intellij IDE on my Windows machine uses Ctrl-D and Eclipse has had problems in the past.

I know this is old. For posterity's sake, I'm posting my experience too. I personally had an issue with scanner and hasNext() looping infinitely. I had called Scanner.close() earlier in the program, when my scanner was based on System.in for input. Remove the close on the scanner and instead instantiating new scanner fixed it for now. As a comment mentions, the scanner was blocked waiting for input so it just reads false always.

Links to the post that helped me: How can I clear the Scanner buffer in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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