Don't ever call nextLine
. Instead, call (once and immediately after creating your scanner), scanner.useDelimiter("\\R");
, and then just call .next()
to read full lines.
This will do what you want.
(Explanation: next()
returns until the next 'token', which is any whitespace by default, but doesn't actually consume this; instead, another nextX()
call would consume it. .nextLine
reads to the next line. This means if you call a next method and then a nextLine method, assuming the user is using the enter key to separate inputs, the nextLine()
method returns a blank string. This isn't what you want, but the real problem is that the default separator of 'any whitespace' isn't what you wanted. You wanted 'a newline' as a separator. \\R
is 'a newline'. This is simpler code, less code, doesn't fail if the user ever decides to use the biggest key on their keyboard (vs. injecting nextLine()
calls to 'eat up the whitespace' which fails if they do that).
Note that the linked answer in the comments gives inferior advice. I'm not sure how to deal with the notion that a question has been asked before, the primary (and accepted) answer on said question is not incorrect but significantly inferior, but there's no snowball's chance any other answer would catch up.