简体   繁体   English

如何为输入的整数设置try / catch

[英]How to set up a try/catch for an integer entered

I would like to know how to set up a try/catch on a variable that is a string but has to be checked against an integer like so: 我想知道如何在一个字符串变量上设置try / catch,但必须像这样对整数进行检查:

public static void isValidAge(String age) {
    int age2 = Integer.parseInt(age);
    try {
        if(age2 <= 0 || age2 >= 150) {
            throw new NumberFormatException();
        }
    }
    catch (NumberFormatException ex) {
        if(age2 <= 0) {
            System.err.print("Age can not be 0 or negative.");
        }
        else if (age2 >= 150) {
            System.err.print("Age can not be equal to or more than 150.");
        }
        else if (age.contains("#@$")) {
            System.err.print("You did not enter a valid age.");
        }
    }
}

The try/catch must also be able to handle characters and keep the program running still. try / catch还必须能够处理字符并使程序保持运行状态。

The try-catch should be on the parse attempt itself: try-catch应该在解析尝试本身上:

 int age2 = -1; //set to an invalid value
 try
 {
    age2 = Integer.parseInt(age);
 }
 catch(Exception ex)
 {
    System.out.println("Error: Could not parse age to number, exiting");
    return; //exit function
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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