Java Scanner不等待用户输入

use*_*389 10 java io java.util.scanner

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

输出:

X:Y :(等待输入)

我的代码

System.out.print("X: ");
x = scanner.nextLine();
System.out.print("Y: ");
y = scanner.nextLine();
Run Code Online (Sandbox Code Playgroud)

任何想法为什么会这样?谢谢

Ale*_* C. 28

你有可能像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();
Run Code Online (Sandbox Code Playgroud)

展示你所看到的行为.

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

你需要消耗'\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();
Run Code Online (Sandbox Code Playgroud)

(实际上是一个更好的方式是直接调用nextLine()nextInt()).

  • @AnubianNoob 我在这个问题上看到的唯一问题是它之前在这里发布过:http://stackoverflow.com/questions/7877529/java-string-scanner-input-does-not-wait-for-info-moves -directly-to-next-stateme?rq=1 (3认同)