我正在使用Java的Scanner来读取用户输入。如果我只使用一次nextLine,它可以正常工作。但是,如果使用两次nextLine,第一个就不等待用户输入字符串(第二个会)。
输出:
X: Y:(等待输入)
我的代码:
System.out.print("X: ");
x = scanner.nextLine();
System.out.print("Y: ");
y = scanner.nextLine();
有什么想法是为什么会发生这种情况吗?谢谢。
我正在使用Java的Scanner来读取用户输入。如果我只使用一次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()
。)