Walton Wang
Walton Wang

Reputation: 409

Do methods execute top to down when called upon by the main method?

Pretty confused as to how the following code works:

static Scanner sc = new Scanner(System.in);

    public static int GetAnInteger()
    {
        while (!sc.hasNextInt())
        {
            sc.nextLine();
            System.out.print("That's not "
                    + "an integer. Try again: ");
        }
        return sc.nextInt();
    }

I understand that .hasNextInt() records a value and serves as a boolean to test whether or not it's a int. .nextLine() records the next line, but how does it debug the loop?

Also when I execute the code, isn't the system supposed to print the statement after I input to .nextLine()?

Upvotes: 1

Views: 57

Answers (1)

Jeremy Hanlon
Jeremy Hanlon

Reputation: 317

The exclamation point means boolean not. So it flips the value of the boolean. True to false. False to true.

A short summary of what this code does in english is the following:

While their is not integer up next, read the next line and ignore the line and print "That's not an integer...". If an integer is the next line, return the next line.

Hope this helps you understand the code better. Comment if you want a more detailed explanation

Upvotes: 2

Related Questions