Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner nextLine() occasionally 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 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?

like image 814
jsan Avatar asked Nov 26 '14 04:11

jsan


1 Answers

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(); 
like image 129
Hovercraft Full Of Eels Avatar answered Sep 23 '22 01:09

Hovercraft Full Of Eels