我正在使用 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()
被执行,所以我的输出是这样的:
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()
按照我的意愿执行。
原文由 blekione 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是因为
Scanner.nextInt
方法不会读取通过按“Enter”创建的输入中的 _换行符_,因此对Scanner.nextLine
的调用在读取该 换行符 后返回。当您在
Scanner.next()
或任何Scanner.nextFoo
方法之后使用Scanner.nextLine
时,您将遇到类似的行为(除了nextLine
本身)。解决方法:
Scanner.nextInt
或Scanner.nextFoo
之后放置一个Scanner.nextLine
调用以消耗该行的其余部分,包括 换行符Scanner.nextLine
读取输入并将您的输入转换为您需要的正确格式。例如,您可以使用Integer.parseInt(String)
方法转换为整数。