Java扫描器不等待用户输入

36

我正在使用Java的Scanner来读取用户输入。如果我只使用一次nextLine,它可以正常工作。但是,如果使用两次nextLine,第一个就不等待用户输入字符串(第二个会)。

输出:

X: Y:(等待输入)

我的代码:

System.out.print("X: ");
x = scanner.nextLine();
System.out.print("Y: ");
y = scanner.nextLine();

有什么想法是为什么会发生这种情况吗?谢谢。


4
当我尝试这个时,它很好地工作。只有在用户输入并按下回车键后,才会打印出y的值。你的Scanner是怎样的?我使用了Scanner scanner = new Scanner(System.in); - Sara S
1个回答

94

你可能在调用像nextInt()这样的方法之前。因此,一个像这样的程序:

Scanner scanner = new Scanner(System.in);
int pos = scanner.nextInt();
System.out.print("X: ");
String x = scanner.nextLine();
System.out.print("Y: ");
String y = scanner.nextLine();

演示了您正在看到的行为。

问题在于nextInt()不会消耗'\n',因此下一次调用nextLine()会将其消耗掉,然后等待读取y的输入。

在调用nextLine()之前,您需要先消耗'\n'

System.out.print("X: ");
scanner.nextLine(); //throw away the \n not consumed by nextInt()
x = scanner.nextLine();
System.out.print("Y: ");
y = scanner.nextLine();

(实际上更好的方法是在 nextInt() 后直接调用 nextLine()。)


4
@AnubianNoob 这个问题唯一的问题在于它之前已经发布在这里:https://dev59.com/i2sz5IYBdhLWcg3weHqU?rq=1 - Jonathan Scialpi

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