shayyy7
shayyy7

Reputation: 93

input a number on scanner

I am trying to create a simple Java program where the user should input his age. If the user entered for example a letter instead of a number, he will get a message.
What I would like to do is that in addition to the message the user should be asked for another input and that input will be checked again to see if it is a number.
Can anyone know how can I achieve that?

System.out.println("2 - Set The Age");
Scanner b = new Scanner(System.in);

if (b.hasNextDouble()) {
    double lage = b.nextDouble();
    setAge(lage);
    addEmployeeMenu();
} else {
    System.out.println("You should type only numbers!");
}

Upvotes: 1

Views: 117

Answers (2)

Jad Chahine
Jad Chahine

Reputation: 7149

You can also use NumberFormatException:

while (true) {
            System.out.println("Set the age: ");
            String input = sc.next();
            try {
                int x = Integer.parseInt(input);
                System.out.println("Your input '" + x + "' is a integer");
                break;
            } catch (NumberFormatException nFE) {
                System.out.println("Not an Integer");
            }
        }

Upvotes: 0

Luigi Cortese
Luigi Cortese

Reputation: 11121

You can use a while loop like this

Scanner b = new Scanner(System.in);
double lage;

while (true) {
    System.out.println("2 - Set The Age");
    if(b.hasNextDouble()){
        lage = b.nextDouble();
        break;
    }else b.nextLine();
}

The point is, get your number and check it inside a while loop, repeat as long as the input is not correct

Upvotes: 3

Related Questions