Java Scanner 不等待用户输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23450524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Scanner doesn't wait for user input
提问by user2976389
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).
我正在使用 Java 的 Scanner 来读取用户输入。如果我只使用 nextLine 一次,它工作正常。有两个 nextLine 第一个不等待用户输入字符串(第二个)。
Output:
输出:
X: Y: (wait for input)
X:Y:(等待输入)
My code
我的代码
System.out.print("X: ");
x = scanner.nextLine();
System.out.print("Y: ");
y = scanner.nextLine();
Any ideas why could this happen? Thanks
任何想法为什么会发生这种情况?谢谢
采纳答案by Alexis C.
It's possible that you are calling a method like nextInt()
before. Thus a program like this:
您可能像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();
demonstatres the behavior you're seeing.
演示您所看到的行为。
The problem is that nextInt()
does not consume the '\n'
, so the next call to nextLine()
consumes it and then it's waiting to read the input for y
.
问题是nextInt()
不消耗'\n'
,所以下一次调用nextLine()
消耗它,然后等待读取 的输入y
。
You need to consume the '\n'
before calling nextLine()
.
您需要'\n'
在调用之前消耗nextLine()
.
System.out.print("X: ");
scanner.nextLine(); //throw away the \n not consumed by nextInt()
x = scanner.nextLine();
System.out.print("Y: ");
y = scanner.nextLine();
(actually a better way would be to call directly nextLine()
after nextInt()
).
(实际上更好的方法是在nextLine()
之后直接调用nextInt()
)。