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

相关文章:

java - Eclipse 说 'MyFirstListener' 未定义,但我已经在我调用的另一个类中定义了它,我不确定出了什么问题

java - 从 clojure 使用 java 第三方库的步骤

java - 我们如何确定文本文件中的行数?

java - 扫描仪跳过循环中第一个输入的输入

Java:我应该使用 float 还是 Float?

java - Launch4J 和 Java Web Start 的组合?

c - 在c中使用fscanf()读取多行

c++ - istream std::cin 如何修改自定义 istream 缓冲区?

java - 使用 Scanner : Why am I getting an error when using Scanner for read files in java? 读取文件

java - 有人能给我解释一下这段代码吗?关于用户输入、扫描仪等