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

相关文章:

java - 在一项测试中无缝使用标准 Fit 夹具和 FitLibrary DoFixture

java - Gwt - 无法加载模块入口点类

Linux : how to redirect to a file and to another process

java.util.Scanner 读取不同字符编码的文件

java - 如何将文件中的多行存储到扫描仪的字符串中`

java - 扫描仪 - 忽略文件末尾的新行

java - 开发图库 View 时 setAdapter 出错

java - Java中Process类的用途是什么?

ruby - IO 对象的约定或经验法则?

java - 在 grails 服务器内运行 .sh 文件