Java Scanner 不等待用户输入 [英] Java Scanner doesn't wait for user input

查看:39
本文介绍了Java Scanner 不等待用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Java 的扫描器来读取用户输入.如果我只使用 nextLine 一次,它工作正常.有两个 nextLine 第一个不等待用户输入字符串(第二个是).

I am using Java's Scanner to read user input. If I use nextLine only once, it works OK. With two nextLine first one doesnt wait for user to enter the string(second does).

输出:

X:Y:(等待输入)

我的代码

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

任何想法为什么会发生这种情况?谢谢

Any ideas why could this happen? Thanks

推荐答案

您可能之前正在调用像 nextInt() 这样的方法.因此,这样的程序:

It's possible that you are calling a method like nextInt() before. Thus a program like this:

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() 不消耗 ' ',所以下一次调用 nextLine() 会消耗它然后等待读取 y 的输入.

The problem is that nextInt() does not consume the ' ', so the next call to nextLine() consumes it and then it's waiting to read the input for y.

您需要在调用 nextLine() 之前使用 ' '.

You need to consume the ' ' before calling nextLine().

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

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

(actually a better way would be to call directly nextLine() after nextInt()).

这篇关于Java Scanner 不等待用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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