gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:05:39 25 4
gpt4 key购买 nike

我想知道如何在一个字符串变量上设置 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.");
}
}
}

try/catch 还必须能够处理字符并保持程序继续运行。

最佳答案

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
}

关于java - 如何为输入的整数设置 try/catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22798541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com