Please Edit your post and wrap your code with
<YOUR CODE HERE>
to get highlighting and preserve formatting.
If you are only entering one word before pressing Enter, use the nextLine() method to read the input from the user.Quote:
problem that I am having is that it is only collecting the first word of the input.
For a test with the current code, try typing both words on the same line before pressing Enter. next() should read one and then the other.
Scanner methods can be tricky. The Scanner buffers input and can block waiting for input.
For example if you enter: A word to the wise <PRESS ENTER>
and use next() only "A" is read, and "word to the wise" is left in the buffer.
Your next attempt to get something from Scanner will be to get "word".
To clear the buffer, use the nextLine() method.
Please explain how that happens. Do you get any error messages?Quote:
nextLine() completely skips my input and essentially closes my program
Can you post the code where that happens and copy the console from when you executed the code.
On windows: To copy the contents of the command prompt window:
Click on Icon in upper left corner
Select 'Select All' - The selection will show
Click in upper left again
Select Edit and click 'Copy'
nextLine() reads a whole line.
next() reads the next token.
You need to enhance your usage of println() to show what is in the String that was read. What if the String returned by nextLine() was empty? Try this:
Your problem is the buffering that Scanner does. next() does not remove the newline character from the buffer. When nextLine() is called it returns an empty line if the buffer has a newline.
Looks like an empty String was read into the g variable(between the = and the <). What method was used to read g?
If the code has called the next() method, there is a newline left in Scanner's buffer.
Call nextLine() to read that from the buffer before using nextLine() to read a whole line.
You need to have your PC's keyboard checked. It's Caps lock is stuck on.