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

2022-01-30 00:00:00 io java java.util.scanner

我正在使用 Scanner 方法 nextInt()nextLine() 来读取输入.

I am using the Scanner methods nextInt() and nextLine() for reading input.

看起来像这样:

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()被执行,这样我的输出如下所示:

The problem is that after entering the numerical value, the first input.nextLine() is skipped and the second input.nextLine() is executed, so that my output looks like this:

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() 都会按照我的意愿执行.

I tested my application and it looks like the problem lies in using input.nextInt(). If I delete it, then both string1 = input.nextLine() and string2 = input.nextLine() are executed as I want them to be.

推荐答案

那是因为 Scanner.nextInt 方法不会读取通过点击Enter," 所以调用 Scanner.nextLine 在读取该 newline 后返回.

在 Scanner.nextLine 时会遇到类似的行为Scanner.html#next%28%29" rel="noreferrer">Scanner.next() 或任何 Scanner.nextFoo 方法(除了 nextLine 本身).

You will encounter the similar behaviour when you use Scanner.nextLine after Scanner.next() or any Scanner.nextFoo method (except nextLine itself).

解决方法:

  • 在每个 Scanner.nextIntScanner.nextFoo 之后调用 Scanner.nextLine 以使用该行的其余部分,包括换行

  • Either put a Scanner.nextLine call after each Scanner.nextInt or Scanner.nextFoo to consume rest of that line including newline

int option = input.nextInt();
input.nextLine();  // Consume newline left-over
String str1 = input.nextLine();

  • 或者,更好的是,通过 Scanner.nextLine 读取输入并将您的输入转换为您需要的正确格式.例如,您可以使用 Integer.parseInt(String) 方法.

  • Or, even better, read the input through Scanner.nextLine and convert your input to the proper format you need. For example, you may convert to an integer using Integer.parseInt(String) method.

    int option = 0;
    try {
        option = Integer.parseInt(input.nextLine());
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    String str1 = input.nextLine();
    

  • 相关文章