NextLine () scanner sometimes skips input

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 he displays this

Last name: First name: 

It basically skips, letting me type in lastNameand goes right into the prompt for firstName.

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

+4
source share
1 answer

Suppose you have code that is not shown that the scanner uses to try to get lastName. In this attempt, you are not processing the end-of-line marker, and therefore it has remained dangling, only to absorb the call nextLine()where you are trying 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 will have problems.

, , EOL, , keyboard.nextLine().

,

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(); 
+8

All Articles