Scanner nextLine() 偶尔跳过输入

5

这是我的代码

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(),它就能正常工作。有任何想法为什么吗?
1个回答

8

让我猜猜 - 你可能有一些没有展示出来的代码在尝试获取 lastName 前使用了 Scanner。在那个尝试中,你没有处理行结束标记,所以它被悬挂着,只能被调用 nextLine() 的代码吞掉,而这段代码试图获取 lastName。

例如,如果你有以下代码:

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

那正是发生的事情。谢谢! - jsan
2
@jsan:不用谢。我们大多数人在刚开始使用Scanner时都会遇到这个问题。另一个可能的解决方案是使用一个Scanner获取行,然后再使用另一个处理行中的文本,只要在使用后关闭所有扫描仪(除了与System.in相关联的那个)。 - Hovercraft Full Of Eels

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接