• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

scanner.hasNext() for System.in

 
Robin John
Ranch Hand
Posts: 281
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Campbell Ritchie
Sheriff
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic