简体   繁体   中英

Try-Catch for user input

I'm trying to make a try-catch statement that catches when the user enters a number less than 0, and then catches if the user enters a char/String considering I want an int from the user.

try {
    System.out.print("How many square feet are on your lot? (Enter 0 to quit): ");
    userSquareFeet = scnr.nextInt();

    if (userSquareFeet < 0) {
        throw new Exception("You can't have a negative value");
    }
} catch (InputMismatchException e) {
    System.out.println("You can not enter a character(s).");
} catch (Exception e) {
    System.out.println(e.getMessage());
}

When I enter a char/String, it just starts up an infinite loop for some reason. Any help is appreciated, sorry for the easy question, Zybooks.com just didn't do a good job on this section in my opinion.

When you use the nextInt() method, the program actually enters a loop until the input is really an integer. Your program input is already type restricting in itself.

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