Java - Scanner - Skips over my last nextLine() req

2020-02-07 05:34发布

问题:

So I instantiate the Scanner scan a lot earlier but it skips right over my second scan.nextLine() after scan.nextInt(). I don't understand why it skips over it?

     System.out.println("Something: ");

        String name = scan.nextLine();

        System.out.println("Something?: ");

        int number = scan.nextInt();

        System.out.println("Something?: ");

        String insurer = scan.nextLine();

        System.out.println("Something?: ");

        String another = scan.nextLine();

回答1:

because when you enter a number

    int number = scan.nextInt();

you enter some number and hit enter, it only accepts number and keeps new line character in buffer

so nextLine() will just see the terminator character and it will assume that it is blank String as input, to fix it add one scan.nextLine() after you process int

for example:

 System.out.println("Something?: ");

 int number = scan.nextInt();

 scan.nextLine(); // <-- 


回答2:

  • The method nextInt() will not consume the new line character \n.So the new line character which was already there in the buffer before the nextInt() will be ignored.
  • Next when you call nextLine() after the nextInt,the nextLine() will consume the old new line
    character left behind and consider the end ,skipping the rest.

Solution

int number = scan.nextInt();
// Adding nextLine just to discard the old \n character
scan.nextLine();

System.out.println("Something?: ");
String insurer = scan.nextLine();

OR

//Parse the string to interger explicitly

String name = scan.nextLine();
System.out.println("Something?: ");
String IntString = scanner.nextLine();

int number = Integer.valueOf(IntString);
System.out.println("Something?: ");
String insurer = scanner.nextLine();


回答3:

When you call int number = scan.nextInt(); it does not consume the carriage return that has been pushed, so this is does at the next scan.nextLine();

You want your code to be

    ....
    System.out.println("Something?: ");
    int number = scan.nextInt();
    scan.nextLine();                      // add this
    System.out.println("Something?: ");
    String insurer = scan.nextLine();


回答4:

All answers given before are more or less correct.

Here is a compact version:

What you want to do: First use nextInt(), then use nextLine()

What is happening: While nextInt() is waiting for your input, you press ENTER key after you type your integer. The problem is nextInt() recognizes and reads only numbers so the \n for the ENTER key is left behind on the console. When the nextLine() comes again, you expect it to wait till it finds \n. But what do you didn't see is that \n is already lying on the console because of erratic behavior of nextInt() [This problem still exists as a part of jdk8u77].

So, the nextLine reads a blank input and moves ahead.

Solution: Always add a scannerObj.nextLine() after each use of scannerObj.nextInt()