简体   繁体   中英

Force user to enter a valid number using the Java scanner

I have a simple code that asks for the age of a user. Everything is working as it should, except, if I type nothing and simply press enter I enter into something - maybe infinite loop? I am not sure but I cannot get out of it.

I have seen countless questions and responses for this topic when dealing with strings but barely any with byte (or int ).

This is my code:

    //App #2: Age

    System.out.print("Enter your Age: ");

    byte age = scanner.nextByte();

    while (!scanner.hasNext()) {
        System.out.println("Please enter a valid number.");
        byte test = scanner.nextByte();
    }

    if (age > 16) {
        applicant.age = age;
        System.out.println(age);
    }
    else
        System.out.println("You must be at least 17 years old to obtain a microloan.");

What can I do to force a user to enter a valid number?

Your loop needs to continue as long as additional input is available (ie, scanner.hasNext() ) but it isn't a valid byte (ie, .scanner.hashNextByte() ). You should also remember to consume ( next() ) any invalid string so the next inputed string can be evaluated:

while (scanner.hasNext() && !scanner.hasNextByte()) {
    System.out.println("Please enter a valid number.");
    scanner.next(); // Discard the invalid string
}

// Now we have a valid byte, read it:
byte age = scanner.nextByte();

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