本文介绍了使用next()或nextFoo()后,Scanner正在跳过nextLine()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用扫描程序方法 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.

推荐答案

那是因为方法不要通过点击Enter来读取输入中的换行符字符,因此调用在读取换行符后返回

That's because the Scanner.nextInt method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner.nextLine returns after reading that newline.

在或任何 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.nextLine 在每个 Scanner.nextInt Scanner.nextFoo 之后调用以消耗该行的其余部分,包括 newline

  • 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读取输入并将输入转换为您需要的正确格式。例如,您可以使用方法。

  • 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();
    


  • 这篇关于使用next()或nextFoo()后,Scanner正在跳过nextLine()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-21 02:42