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

相关文章:

c - *non-blockingness* 的 libuv 实现是如何工作的?

c - fork() 进程中的 IO 流

Java util.Scanner 无法立即识别用户输入

java - 如何使用 Java Scanner 读取命题逻辑符号作为输入?

java - 如何将 CSV 文件中的数据输入到我的代码中?

java - Jar 文件找不到 keystore

java - 为什么 java.library.path 在 ubuntu 上不起作用?

java - 无法在java服务器和android客户端之间建立连接

java - 如何用资源链接替换 ​​Swagger 的枚举?

c++ - 当你想明确指定缓冲区大小时,你应该使用 fread/fwrite 还是 read/write 系统调用?