3

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();
    }
}
Tiny
  • 27,221
  • 105
  • 339
  • 599
Alex Zaitsev
  • 2,013
  • 4
  • 30
  • 56

2 Answers2

4

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();
Luke Willis
  • 8,429
  • 4
  • 46
  • 79
Grim
  • 1,938
  • 10
  • 56
  • 123
2

Because you are using nextInt() this method only grabs the next int it doesn't consume the \n character so the next time you do nextLine() it finishes consuming that line then moves to the next line.

brso05
  • 13,142
  • 2
  • 21
  • 40