Scanner nextLine()偶尔会跳过输入 [英] Scanner nextLine() occasionally skips input

查看:137
本文介绍了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 的提示符。

Basically it skips letting me enter lastName and goes straight to the prompt for firstName.

但是,如果我使用 keyboard.next()而不是 keyboard.nextLine( ),它工作正常。任何想法为什么?

However, if I use keyboard.next() instead of keyboard.nextLine(), it works fine. Any ideas why?

推荐答案

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

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.

例如,如果你有这个:

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()吞下它。

One solution, whenever you leave the EOL token dangling, swallow it by calling 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(); 

这篇关于Scanner nextLine()偶尔会跳过输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆