1

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?

1 Answer 1

3

Your loop needs to continue as long as additional input is available (i.e., scanner.hasNext()) but it isn't a valid byte (i.e., !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();
Sign up to request clarification or add additional context in comments.

1 Comment

Got ya. That makes sense. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.