[java] Using scanner.nextLine()

I have been having trouble while attempting to use the nextLine() method from java.util.Scanner.

Here is what I tried:

import java.util.Scanner;

class TestRevised {
    public void menu() {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a sentence:\t");
        String sentence = scanner.nextLine();

        System.out.print("Enter an index:\t");
        int index = scanner.nextInt();

        System.out.println("\nYour sentence:\t" + sentence);
        System.out.println("Your index:\t" + index);
    }
}

Example #1: This example works as intended. The line String sentence = scanner.nextLine(); waits for input to be entered before continuing on to System.out.print("Enter an index:\t");.

This produces the output:

Enter a sentence:   Hello.
Enter an index: 0

Your sentence:  Hello.
Your index: 0

// Example #2
import java.util.Scanner;

class Test {
    public void menu() {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\nMenu Options\n");
            System.out.println("(1) - do this");
            System.out.println("(2) - quit");

            System.out.print("Please enter your selection:\t");
            int selection = scanner.nextInt();

            if (selection == 1) {
                System.out.print("Enter a sentence:\t");
                String sentence = scanner.nextLine();

                System.out.print("Enter an index:\t");
                int index = scanner.nextInt();

                System.out.println("\nYour sentence:\t" + sentence);
                System.out.println("Your index:\t" + index);
            }
            else if (selection == 2) {
                break;
            }
        }
    }
}

Example #2: This example does not work as intended. This example uses a while loop and and if - else structure to allow the user to choose what to do. Once the program gets to String sentence = scanner.nextLine();, it does not wait for input but instead executes the line System.out.print("Enter an index:\t");.

This produces the output:

Menu Options

(1) - do this
(2) - quit

Please enter your selection:    1
Enter a sentence:   Enter an index: 

Which makes it impossible to enter a sentence.


Why does example #2 not work as intended? The only difference between Ex. 1 and 2 is that Ex. 2 has a while loop and an if-else structure. I don't understand why this affects the behavior of scanner.nextInt().

This question is related to java java.util.scanner

The answer is


Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.


or

int selection = Integer.parseInt(scanner.nextLine());

Rather than placing an extra scanner.nextLine() each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)

import java.util.Scanner;

class ScannerTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\\n");

        System.out.print("Enter an index: ");
        int index = scanner.nextInt();

        System.out.print("Enter a sentence: ");
        String sentence = scanner.next();

        System.out.println("\nYour sentence: " + sentence);
        System.out.println("Your index: " + index);
    }
}

Thus, to read a line of input, you only need scanner.next() that has the same behavior delimiter-wise of next{Int, Double, ...}

The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also <space>3, 3<space> and 3<space>whatever while the former only accepts 3 on a line on its own


It's because when you enter a number then press Enter, input.nextInt() consumes only the number, not the "end of line". Primitive data types like int, double etc do not consume "end of line", therefore the "end of line" remains in buffer and When input.next() executes, it consumes the "end of line" from buffer from the first input. That's why, your String sentence = scanner.next() only consumes the "end of line" and does not wait to read from keyboard.

Tip: use scanner.nextLine() instead of scanner.next() because scanner.next() does not read white spaces from the keyboard. (Truncate the string after giving some space from keyboard, only show string before space.)