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/60307525/

相关文章:

java - 使用 Apache fop 时条形码未显示在 pdf 上

java - 如何在Java中注释导入声明?

java - 使用 Volley 为 JSON 请求自定义对象绑定(bind)

c++在类方法中使用cout

go - scanner.Scan() 在 Linux 但不是 Windows 上阻塞直到退出

java - 使用 PDFBox jar 文件打印 PDF 文件

c - 使用 sigaction() 进行 I/O 处理

java - java Scanner 类中的 nextLine()、hasNextLine() 和 NoSuchElementException

java - 这是后缀计算器程序,我遇到无法识别的操作数错误

java - 写入一个 Double 数字以便稍后使用 Scanner.nextDouble() 读取