Scanner is skipping nextLine() after using next() or nextFoo()?
To resolve Java's Scanner
issue where next()
or nextFoo()
are not digesting the newline (\n
), drop in a scanner.nextLine()
after these methods. This will chow down on the remaining newline, priming the next nextLine()
to read the complete forthcoming user input successfully.
The rule of thumb : consistently add nextLine()
after next()
, nextInt()
, etc., to reorient Scanner for correct line inputs.
Exploring the next() and nextFoo() methods
In next()
or nextFoo()
encounters, Scanner
whitewashes till it spots a delimiter (usually, it's the whitespace invader). However, as soon as it uncovers the token it needs, it hits a dead end, leaving the newline twiddling its thumbs in the input buffer.
To free ourselves from this issue, invariably attach a scanner.nextLine()
after the type-specific nextFoo()
methods:
We can also convert the captivated string into an integer for better error handling control:
Decoding the underpinnings
Scanner
input methods: A nutshell tour
nextInt()
and like-minded methods are not just selfish, they refuse to die young—meaning, they stop reading right before reaching the newline.Scanner.nextLine()
picks up every single character, right up to and including the newline.- Blending
nextInt()
andnextLine()
typically results in a not-so-tasty smoothie a.k.a unexpected behavior.
Newline characters: Same same but different
- Windows prefers its line endings like most prefer their pizzas - with extra cheese, or
\r\n
. - UNIX/Linux keeps it simple with
\n
. - The older gen Macs (up to OS 9) roll with
\r
.
Yet, Scanner
usually treats all these as the end of a line.
Clearing the buffer vs skipping characters
- Opt for
scanner.nextLine()
to gobble up any freeloading newline characters. - For those pesky optional
\r
or avoiding line breaks, bring inscanner.skip("\\R?")
to the rescue.
Straight to the point code snippets
Classy example leveraging skip patterns
Error handling par excellence
Was this article helpful?