Forums Register Login

Regrading the Scanner object

+Pie Number of slices to send: Send
Here's the basic structure of my program till now:


On line 23: Why doesn't the 'choice' work with existing Scanner object?
If I remove line 23 then the program doesn't wait for my input.
Any help is much appreciated!
Thanks in advance!!
+Pie Number of slices to send: Send
This is down to the fact that nextLine() works differently to the other next() methods.
If you only want a single "word" (ie no spaces in the input) then use next(), otherwise you'll need to make two calls to nextLine().

The reason is that the regular nextXXX() methods read up to the next token (in the default Scanner that is a whitespace character, so space, tab, new line etc), they do no, however, read that character, so it is still in the buffer.

So reading in:
1
with nextInt() will leave a new line in the buffer.

Now, nextLine() reads in up to and including the next new line character (it discards the new line). So, after the above nextInt, if I then do a nextLine() it will read in that new line that has been left in the buffer, and return an empty String.
+Pie Number of slices to send: Send
Whoa! Mind blowing!! Thanks a lot!!
+Pie Number of slices to send: Send
 

Ashwin Rao wrote:Whoa! Mind blowing!! Thanks a lot!!



I ought to keep that one in my past buffer, to be honest.

It comes up a lot, which (to me) implies a problem with how Scanner was designed.
+Pie Number of slices to send: Send
In fact, in comes up so often we have a couple of FAQs that address that very issue. Here and here.
+Pie Number of slices to send: Send
 

Dave Tolls wrote:This is down to the fact that nextLine() works differently to the other next() methods. . . .

Or that people are not taught about it. I have yet to see a book with a good explanation of nextLine().
+Pie Number of slices to send: Send
 

Campbell Ritchie wrote:

Dave Tolls wrote:This is down to the fact that nextLine() works differently to the other next() methods. . . .

Or that people are not taught about it. I have yet to see a book with a good explanation of nextLine().



I have yet to see a decent explanation of Scanner as a whole.
It just looks (to me) like it's been cobbled together.
I am not a spy. Definitely. Definitely not a spy. Not me. No way. But this tiny ad ...
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 460 times.
Similar Threads
Having troubles with a complex program, need help with an illegal start of type error.
ERROR - "system cannot find the file specified"
Question About Scanner Class and nextInt(), nextLine(), and next() Methods
Java — Closing Scanner and Resource Leak
String scans acting screwy?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 08:20:05.