Reputation:
When do I need to scan in an extra line by using .nextLine()
to pick up the \n
due to the enter key from the previous scan? What i mean to ask is, after what kind of scan statements do i need to have an extra scan line to pick up the \n
. .next().nextDouble()
.nextInt? I tried looking online, but couldn't find an answer to this.
Upvotes: 0
Views: 108
Reputation: 79877
Whenever you use next()
or any of the other Scanner
methods that read a token, any white space that follows the token remains in the Scanner
. That includes a newline character, if that happens to be the character that follows the token. This is OK most of the time.
When you use nextLine()
, what gets read is everything up to and including the next end-of-line. This is OK if you want an entire line of text.
The problem is when you mix these two strategies. If you have a line that contains a single token, and you read it with next()
(or nextInt()
, nextDouble()
or any of the similar methods), then the following call to nextLine()
will just read the end-of-line that follows the token, as opposed to the next line. This is the one case when you need an extra nextLine()
call.
For an example of the sort of program where you need this, see java string variable using .next() or .nextLine() where the OP has a call to nextInt()
followed by a call to nextLine()
without the "extra" nextLine()
call.
Upvotes: 5