Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner nextLine issue in Java [duplicate]

Just one question: why I must type answer = in.nextLine(); twice? If this line is single the program doesn't work as expected. Without second line the program doesn't ask you to enter a string.

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        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.");
                return;
            }

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

        System.out.println("Bye!");
        in.close();
    }
}
like image 351
rocknow Avatar asked Apr 29 '26 06:04

rocknow


1 Answers

The Scanner-Object has an internal cache.

  1. You start the scann for nextInt().
  2. You press the key 1
  3. You press the key 2
  4. You press return

Now, the internal Cache has 3 characters and the scanner sees the third character(return) is not a number, so the nextInt() will only return the integer from the 1st and 2nd character (1,2=12).

  1. nextInt() returns 12.

Unfortunately the return is still part of the Scanner's cache.

  1. You call nextLine(), but the Method scans its cache for a newline-marker that has been kept in the cache from before the nextInt() call returned.

  2. The nextLine() returns a 0-length-string.

  3. The next nextLine() has an empty cache! It will wait until the cache has been filled with the next newline-marker.

reset()

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

in.reset();
like image 183
Grim Avatar answered Apr 30 '26 19:04

Grim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!