本文介绍了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).

输出:

我的代码

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

展示您所看到的行为。

demonstatres the behavior you're seeing.

问题是 nextInt()不消耗'\ n' ,所以下一次调用 nextLine()会消耗它,然后等待读取 y

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.

在调用'\ n' > nextLine()。

You need to consume the '\n' before calling 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();

(实际上更好的方法是直接拨打 nextLine() nextInt()之后。

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

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

08-30 23:37