Meaningless Drivel is fun!*
The moose likes I/O and Streams and the fly likes scanner.hasNext() for System.in Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "scanner.hasNext() for System.in" Watch "scanner.hasNext() for System.in" New topic
Author

scanner.hasNext() for System.in

Robin John
Ranch Hand

Joined: Sep 10, 2008
Posts: 270

Hi All,

Why cant I end the loop and break off from my application when I use a Scanner?
why scanner.hasNext() always returns me true for (System.in)?

Is there any way, I can break off the while scanner.hasNext() loop ? I dont want any end of line indicator to be given by the user..

Please advice, thanks in advance!


Time is what we want the most, but what we use the worst. -- William Penn
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38020
    
  22
I made a similar mistake a few weeks back and Rob Prime pointed it out to me. What follows might be what you want.Note you mightn't need to test for a next token, but a next token of a particular type. In the case of System.in there might always be a "next token", so your loop will never terminate. You need to read the next token before testing to see whether you have found what you want. The hasNext() and hasNextLine() methods are useful when reading from files, where there always is a "last line". Occasionally there seem to be tokens which get out of step with what you expect; a next() call may be necessary to get rid of an unwanted token.

Note also the documentation says the hasNext() method may block while awaiting input, so that is an alternative explanation for your problem.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: scanner.hasNext() for System.in
 
Similar Threads
How to compare String and int?
How to break c:forEach iteration?
parse a string
Loops and try...catch
Scanner question