提问者:小点点

扫描程序在使用next()或nextFoo()后是否跳过nextLine()?


我正在使用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()都将按我希望的方式执行。


共3个答案

匿名用户

这是因为scanner.NextInt方法不读取通过单击“Enter”创建的输入中的换行符,因此对scanner.NextLine的调用在读取该换行符后返回。

当您在scanner.nextLine之后使用scanner.nextLine或任何scanner.nextfoo方法(除了nextLine本身)时,您将遇到类似的行为。

解决方法:

>

  • 在每个scanner.NextLinescanner.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();
    

  • 匿名用户

    问题出在input.nextInt()方法上--它只读取int值。 因此,当您继续使用input.nextline()读取时,您将收到“\n”Enter键。 所以要跳过这个,必须添加input.nextline()。 希望现在能搞清楚。

    试试看:

    System.out.print("Insert a number: ");
    int number = input.nextInt();
    input.nextLine(); // This line you have to add (It consumes the \n character)
    System.out.print("Text1: ");
    String text1 = input.nextLine();
    System.out.print("Text2: ");
    String text2 = input.nextLine();
    

    匿名用户

    这是因为当您输入一个数字,然后按enter时,input.NextInt()只使用该数字,而不使用“行尾”。 当input.NextLine()执行时,它会消耗从第一个输入开始仍在缓冲区中的“行尾”。

    相反,在input.NextInt()之后立即使用input.NextLine()