Welcome to the Ranch
The reason for that problem is that the
nextLine() method isn't well named and so many of the book authors believe its name reflects its functionality; this
API link tells you what it actually does. Please tell us what your book says it does.
What happens after
nextInt()‑<line‑terminator> is that the Scanner reads the remainder of the line, which in this case contains no useful information, and after that all your inputs are out of sequence, just like what Carey said. It is only a matter of time before you can't match an input, and suffer an exception. I used to call
nextLine() twice, but have since hit on a better solution: create a utility class. You can now write
KeyboardInputs.nextLine() and even use Scanner's ability to read ahead. The following code will happily handle input like this:-
123 JonP Lee
...and this is an example of how you can write a
nextLine() method:-
Pre-Java11 code used
trim() instead of
strip(). The
message would read something like, “Please write name‑<enter>: ” Remember that unlike many Scanner methods,
nextLine() is dependent on a line end sequence being used and its input depends on the location of that line end.