craftdeer
craftdeer

Reputation: 1037

How to use hasNextInt in Java to check if the entered value is integer or not?

I am trying to make a program that asks the user to enter age and loop until the age is positive or a number. When I enter negative number, the look works and it asks to enter the number again but when I enter letters like "xyz" instead, the loop doesn't work and and the program crashes.

public static void firstScannerMethod () {
        Scanner scanner = new Scanner(System.in); //importing scanner class
        System.out.println("enter your age: ");
        boolean hasNextIntAge = scanner.hasNextInt(); //checking to see if next entered value is an integer
        int myAge = scanner.nextInt();
        scanner.nextLine(); //handling enter
        while (myAge < 0 || !hasNextIntAge) { // if age is less than 0 or if age is not an integer, prompt again
            System.out.println("invalid age, try again");
            System.out.println("enter your age: ");
            myAge = scanner.nextInt();
            scanner.nextLine();
        }
            System.out.println("your age is " + myAge);
        scanner.close();
}

Upvotes: 0

Views: 921

Answers (1)

D George
D George

Reputation: 188

You are not checking the value of hasNextIntAge before calling the nextInt method. As a result, when nextInt gets a string value it throws an InputMismatchException. I have updated your code to set myAge only if the input is an integer.

public static void firstScannerMethod () {
    Scanner scanner = new Scanner(System.in);
    System.out.println("enter your age: ");
    while (!scanner.hasNextInt()) {
        System.out.println("invalid age, try again");
        scanner.next();
    }
    int myAge = scanner.nextInt();
    while (myAge < 0) {
        System.out.println("invalid age, try again");
        while (!scanner.hasNextInt()) {
            System.out.println("invalid age, try again");
            scanner.next();
        }
        myAge = scanner.nextInt();
    }
    System.out.println("your age is " + myAge);
    scanner.close();
}

Upvotes: 1

Related Questions