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
posted 6 years ago
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.