简体   繁体   中英

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!");
}

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

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");
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM