| Author |
Help needed with Scanner
|
jishnu dasgupta
Ranch Hand
Joined: Mar 11, 2011
Posts: 103
|
|
I am trying to run this following code using scanner to obtain the tokens:
However when i am taking the input from the console using the Scanner, the while loop correctly parses the tokens, but then it keeps on looping in endless loop, and the program execution does not stop.
If i change the Scanner object to take the input from command line i.e
The while loop correctly terminates after parsing out the tokens.
can you please explain why the while loop does not terminate when i am taking input from the user, and is there a way to make the while loop correctly terminate while doing the same
|
If debugging is the process of removing bugs, then programming must be the process of putting them in. -- Edsger Dijkstra
|
 |
Luigi Plinge
Ranch Hand
Joined: Jan 06, 2011
Posts: 441
|
|
|
System.in is a stream, so Scanner has to wait to see what comes in. If it finished as soon as there was a break in the stream, it wouldn't wait for you to type anything in. So while the stream exists, it assumes there is something else coming. If you just want to wait for 1 token, just remove the while loop and the code should work.
|
 |
jishnu dasgupta
Ranch Hand
Joined: Mar 11, 2011
Posts: 103
|
|
Is there any way that i can place some condition in my while loop, so that after parsing the tokens in my stream the program exists.
say for example, if i enter the input string as: "Hello i am jishnu";
it parses the String and then the program exists.
|
 |
Luigi Plinge
Ranch Hand
Joined: Jan 06, 2011
Posts: 441
|
|
|
Try Scanner's nextLine() method, which will return the whole line, and use String.split on that.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32708
|
|
Luigi Plinge wrote:Try Scanner's nextLine() method, which will return the whole line . . .
Not quite. It returns whatever remains until the next line end. There is lots of potential for confusion about that.
|
 |
jishnu dasgupta
Ranch Hand
Joined: Mar 11, 2011
Posts: 103
|
|
Hi Luigi,
It didnt work with the nextLine()....is there any alternative??
|
 |
Luigi Plinge
Ranch Hand
Joined: Jan 06, 2011
Posts: 441
|
|
|
Works fine for me -
|
 |
jishnu dasgupta
Ranch Hand
Joined: Mar 11, 2011
Posts: 103
|
|
Oh!!...I had that String.split() condition wrong...Thanks anyways!!!...
|
 |
 |
|
|
subject: Help needed with Scanner
|
|
|