Scanner nextLine() occasionally skips input

2019-05-06 18:42发布

问题:

Here is my code

Scanner keyboard = new Scanner(System.in);

System.out.print("Last name: ");
lastName = keyboard.nextLine(); 

System.out.print("First name: ");
firstName = keyboard.nextLine();

System.out.print("Email address: ");
emailAddress = keyboard.nextLine();

System.out.print("Username: ");
username = keyboard.nextLine();

and it outputs this

Last name: First name: 

Basically it skips letting me enter lastName and goes straight to the prompt for firstName.

However, if I use keyboard.next() instead of keyboard.nextLine(), it works fine. Any ideas why?

回答1:

Let me guess -- you've got code not shown that uses the Scanner above the attempt to get lastName. In that attempt, you're not handling the end of line token, and so it's left dangling, only to be swallowed by the call to nextLine() where you attempt to get lastName.

For example, if you have this:

Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = keyboard.nextInt();  // dangling EOL token here
System.out.print("Last name: ");
lastName = keyboard.nextLine(); 

You're going to have problems.

One solution, whenever you leave the EOL token dangling, swallow it by calling keyboard.nextLine().

e.g.,

Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = keyboard.nextInt();  
keyboard.nextLine();  // **** add this to swallow EOL token
System.out.print("Last name: ");
lastName = keyboard.nextLine();