java – Scanner nextLine()偶尔会跳过输入

这是我的代码

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

它输出这个

Last name: First name:

基本上它会跳过让我输入lastName并直接进入firstName的提示符.

但是,如果我使用keyboard.next()而不是keyboard.nextLine(),它可以正常工作.有什么想法吗?

让我猜一下 – 你没有显示使用上面尝试获取lastName的扫描器的代码.在那次尝试中,你没有处理行尾令牌,所以它是悬空的,只是被你试图获取lastName的nextLine()调用吞噬.

例如,如果你有这个:

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

你会遇到问题.

一种解决方案,每当你离开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();
相关文章
相关标签/搜索