我正在使用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)
问题在于输入数字值后,第一个input.nextLine()
被跳过执行了,而第二个input.nextLine()
被执行了,因此我的输出看起来像这样:
问题是在输入数值后,第一个 input.nextLine()
被跳过了,而第二个 input.nextLine()
被执行了,导致我的输出结果如下:
Enter numerical value
3 // This is my input
Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped
Enter 2nd string // ...and this line is executed and waits for my input
我测试了我的应用程序,看起来问题出在使用input.nextInt()
上。如果我删除它,那么string1 = input.nextLine()
和string2 = input.nextLine()
就会像我希望的那样执行。