Java Scanner不等待用户输入

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

输出:

X:Y :(等待输入)

我的代码

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

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

你之前可能正在调用像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() nextInt() )。

只需为您的代码尝试此构造构造:

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