Scanner nextLine() occasionally skips input

不羁的心 提交于 2019-12-07 10:10:25

问题


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


来源:https://stackoverflow.com/questions/27141183/scanner-nextline-occasionally-skips-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!