Warm tip: This article is reproduced from serverfault.com, please click

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

(java - Scanner is skipping nextLine() after using next() or nextFoo()?)

发布于 2012-10-27 16:37:01

我正在使用这些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()执行,我希望他们能。

Questioner
blekione
Viewed
11
33 2018-10-31 09:31:29

这是因为该Scanner.nextInt方法不会在你按“ Enter”键创建的输入中读取换行符,因此Scanner.nextLine在读取该换行符后对return的调用

当你使用Scanner.nextLineafterScanner.next()或任何Scanner.nextFoo方法(nextLine本身除外时,你将遇到类似的行为

解决方法:

  • Scanner.nextLine在每个电话号码之后拨打电话,Scanner.nextIntScanner.nextFoo使用电话号码的其余部分(包括换行符)

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