我使用 Scanner nextInt() 和nextLine() 来读取输入。
酱紫的:
System.out.println("Enter numerical value"); int option;
option = input.nextInt(); // Read numerical value from inputSystem.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 value3 // This is my inputEnter 1st string // The program is supposed to stop here and wait for my input, but is skippedEnter 2nd string // ...and this line is executed and waits for my input
我测试了应用程序,好像问题在于使用input.nextInt()。 如果我删除它,那么 string1 = input.nextLine() 和string2 = input.nextLine()都会执行。
input.nextInt() 是需要输入 int 数值类型的吧。从程序来看,Scanner 没有关闭,是可以重复使用的。
这是因为Scanner.nextInt 不读取输入中通过点击“ Enter”创建的换行符,因此对 Scanner.nextLine 的return在读取换行符后返回。
在 Scanner.next ()或任何 Scanner.nextFoo 方法(nextLine 本身除外)之后使用 Scanner.nextLine 时,也会遇到类似的行为。
换个方法:
要么在每个 Scanner.nextInt 或 Scanner.nextFoo 后面放一个 Scanner.nextLine 调用,以消耗该行的其余部分,包括 newline
int option = input.nextInt();
input.nextLine(); // Consume newline left-overString str1 = input.nextLine();
或者,更好的方法是,通过 Scanner.nextLine 读取输入,并将输入转换为所需的正确格式。 例如,您可以使用 Integer.parseInt (String)方法转换为整数。
int option = 0;try {
option = Integer.parseInt(input.nextLine());} catch (NumberFormatException e) {
e.printStackTrace();}String str1 = input.nextLine();
问题在于 input.nextInt ()方法——它只读取 int 值。因此,当您继续使用 input.nextLine ()进行阅读时,会有"\n" Enter key。 因此,要跳过这一步,您必须添加 input.nextLine ()。 希望这一点现在应该清楚了。
试试这样:
System.out.print("Insert a number: ");int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)System.out.print("Text1: ");String text1 = input.nextLine();System.out.print("Text2: ");String text2 = input.nextLine();
这是因为当您输入一个数字然后按 Enter 键时,input.nextInt ()只consume数字,而不是“行尾”。 当 input.nextLine ()执行时,它将消耗第一个输入中仍在缓冲区中的“行尾”。
可以这样:在 input.nextLine ()后立即使用 input.nextInt ()
关于这个问题, java.util.Scanner似乎问题挺多。我认为一个更容易的解决方案是调用 scanner.skip("[\r\n]+"),在调用 nextInt()之后删除任何换行字符。