【问题标题】:Java Scanner doesn't wait for user input [duplicate]Java Scanner 不等待用户输入 [重复]
【发布时间】:2014-06-20 11:01:20
【问题描述】:

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

输出:

X:Y:(等待输入)

我的代码

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

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

【问题讨论】:

  • 当我尝试这个时它工作正常。 y 只有在用户输入并输入后才会打印出来。你的扫描仪看起来怎么样?我使用了 Scanner 扫描仪 = new Scanner(System.in);

标签: java io java.util.scanner


【解决方案1】:

您之前可能调用过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())。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-01-13
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 2021-03-05
  • 2013-05-25
  • 1970-01-01
  • 2013-12-30
相关资源
最近更新 更多