Nick
Nick

Reputation: 2970

Only accept positive integers using try catch and while

I'm writing a script where the user can only input positive integers. I'm using a scanner with try catch and a while loop. The loop is to keep asking the user for a correct input.

I can check for negative integers, but what about strings or some other crazy stuff?

    int price = 0;
    Scanner input = new Scanner(System.in);
    try {
        System.out.println("Enter max price: ");
        price = input.nextInt();
        if (price > 0) {
            input.close();
        } else {
            while (price < 0) {
                System.out.println("Negative values not allowed");
                System.out.println("Enter max price: ");
                price = input.nextInt();
            }
            input.close();
        }
    } catch (InputMismatchException e1) {

    }

I'm kind of stuck at the catch part..

Upvotes: 1

Views: 3234

Answers (1)

Zong
Zong

Reputation: 6230

Invoke input.hasNextInt() to check if the next token is actually an integer. There is a lot of useful methods in Scanner, so I'd advise taking a look at the docs.

Upvotes: 2

Related Questions