It's not a secret anymore!
The moose likes I/O and Streams and the fly likes scanner.hasNext() for Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "scanner.hasNext() for" Watch "scanner.hasNext() for" New topic

scanner.hasNext() for

Robin John
Ranch Hand

Joined: Sep 10, 2008
Posts: 281

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 (

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

Joined: Oct 13, 2005
Posts: 46320
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 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.
I agree. Here's the link:
subject: scanner.hasNext() for
It's not a secret anymore!