我正在使用这些Scanner方法nextInt()并nextLine()阅读输入.
它看起来像这样:
System.out.println("Enter numerical value");
int option;
option = input.nextInt(); // Read numerical value from input
System.out.println("Enter 1st string");
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)
Run Code Online (Sandbox Code Playgroud)
问题是输入数值后,第一个input.nextLine()被跳过而第二个input.nextLine()被执行,所以我的输出如下所示:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and …Run Code Online (Sandbox Code Playgroud) 我正在创建一个简单的故事,偶尔会提示用户点击ENTER.它第一次提示它时工作,但它会立即执行其他提示,可能是因为当你按ENTER键时程序运行得如此之快,它已经检查了提示.
有任何想法吗?代码如下.
System.out.println("...*You wake up*...");
System.out.println("You are in class... you must have fallen asleep.");
System.out.println("But where is everybody?\n");
promptEnterKey();
System.out.println("You look around and see writing on the chalkboard that says CBT 162");
promptEnterKey();
//////////////////////////////////////////////////////
public void promptEnterKey(){
System.out.println("Press \"ENTER\" to continue...");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud) 我正在使用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)
任何想法为什么会这样?谢谢