扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

新手上路,请多包涵

我正在使用 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 许可协议

阅读 607
2 个回答

这是因为 Scanner.nextInt 方法不会读取通过按“Enter”创建的输入中的 _换行符_,因此对 Scanner.nextLine 的调用在读取该 换行符 后返回。

当您在 Scanner.next() 或任何 Scanner.nextFoo 方法之后使用 Scanner.nextLine 时,您将遇到类似的行为(除了 nextLine 本身)。

解决方法:

  • 在每个 Scanner.nextIntScanner.nextFoo 之后放置一个 Scanner.nextLine 调用以消耗该行的其余部分,包括 换行符
  int option = input.nextInt();
  input.nextLine();  // Consume newline left-over
  String 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();

原文由 Rohit Jain 发布,翻译遵循 CC BY-SA 4.0 许可协议

问题出在 input.nextInt() 方法;它只读取 int 值。因此,当您继续阅读 input.nextLine() 时,您会收到“\n”回车键。所以要跳过这个你必须添加 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();

原文由 Prine 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题