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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With