Scanning nextLine in Java

Just one question: why would I enter twice answer = in.nextLine();

? If this line is single, the program does not work as expected. Without the second line, the program doesn't ask you to enter a line.

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(;
        String answer = "Yes";

        while (answer.equals("Yes")) {
            System.out.println("Enter name and rating:");
            String name = in.nextLine();
            int rating = 0;

            if (in.hasNextInt()) {
                rating = in.nextInt();
            } else {
                System.out.println("Error. Exit.");

            System.out.println("Name: " + name);
            System.out.println("Rating: " + rating);
            ECTS ects = new ECTS();
            rating = ects.checkRating(rating);
            System.out.println("Enter \"Yes\" to continue: ");
            answer = in.nextLine();
            answer = in.nextLine();




source to share

2 answers

Scanner-Object has an internal cache.

  • You run scann for nextInt()

  • You press the key 1
  • You press the key 2
  • You push return

Now the internal cache has 3 characters and the scanner sees that the third character ( return) is not a number, so it nextInt()

only returns an integer between the 1st and 2nd characters ( 1, 2= 12).

  1. nextInt()

    returns 12.

Unfortunately, returnit is still part of the scanner cache.

  1. You call nextLine()

    , but the Method looks in its cache for the newline

    token that was stored in the cache before the call was returned nextInt()


  2. nextLine()

    returns a string of length 0.

  3. The next one nextLine()

    has an empty cache! It will wait until the cache is filled with the next newline


reset ()

There is a more elegant way to clear the cache instead of using nextLine()






Since you are using nextInt (), this method only captures the next int, it does not consume the \ n character, so the next time you do nextLine () it ends up consuming that line, then goes to the next line.



All Articles