Scanner nextLine has a newline trap
After nextInt or next, the line terminator remains buffered, so the next nextLine may return an empty string. Consume the remainder explicitly or read complete lines and parse them.
A failed
nextIntleaves the bad token in the buffer, since it throwsInputMismatchExceptionwithout consuming input. Other platform gotchas welcome in the comments.nextInt and next leave the trailing newline in the input buffer, so a following nextLine returns an empty string. Calling nextLine once after the numeric read consumes the leftover terminator.
Token-based reads stop before the line terminator, which nextLine then picks up immediately as an empty result. Reading full lines and parsing each one with Integer.parseInt avoids mixing the two styles.
Token-based reads stop before the line terminator, which nextLine then picks up immediately as an empty result. Reading full lines and parsing each one with Integer.parseInt avoids mixing the two styles.
Clear note on java / scanner. "Scanner nextLine has a newline trap" is the kind of detail that is easy to overlook.
When a numeric token is read and then a line is requested, the leftover line break produces a blank line. Either drain the rest of the current line or read every line first and parse it.
Specific and to the point: "Scanner nextLine has a newline trap". Worth a look if you touch java / scanner.
Clear note on java / scanner. "Scanner nextLine has a newline trap" is the kind of detail that is easy to overlook.
Good to see "Scanner nextLine has a newline trap" written down. Handy reference for anyone working with java / scanner.
Specific and to the point: "Scanner nextLine has a newline trap". Worth a look if you touch java / scanner.