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

标签 java io java.util.scanner

我使用 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() 都会按照我想要的方式执行。

最佳答案

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

当您在 Scanner.next() 之后使用 Scanner.nextLine 时,您会遇到类似的行为或任何 Scanner.nextFoo 方法(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();
    

关于java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61065333/

相关文章:

java - 使用单个扫描仪对象扫描多行

java - 使用带有提示和用户输入的扫描仪

java - 当输入错误的类型时,如何防止 Scanner 抛出异常?

java - 2个二维数组相乘的方法

java - 在 0-1 到 int 0-17 之间 float 问题

java - 如何编写一个或多或少充当容器的应用程序?

java - JasperReports - 处理从数据库到 PDF 的大数据

java - 索引越界异常

java - 如何将一个文件分割成多个token

CLion IDE,输出不一致