gpt4 book ai didi

java - 如何捕获 NumberFormatException?

转载 作者:行者123 更新时间:2023-12-02 10:11:51 28 4
gpt4 key购买 nike

我正在尝试找出如何在代码中捕获数字格式异常错误,这样如果用户在字符串中输入字母并且我的程序尝试将其解析为 int 我的程序将不会抛出错误而是停止并返回一个 boolean 值。我还试图了解,如果 try 语句有效,我希望它继续执行以下代码。

    if (counter == 3) {
int compare;
boolean check = true;
String[] newip = IpAddress.split("\\.");
if (newip.length == 4) {
for (int index = 0; index < newip.length; index++) {
//There should be a try statement here.
// if the try statement fails then I'd like for it to catch
// the numberformatexception and evaluate my boolean to
//false;
//but if it passes I'd like for it to continue to execute
//the following code.
compare = Integer.parseInt(newip[index]);
if (compare >= 0 & (compare <= 255)) {
check = true;
}
else{
check = false;
}
}
if (check)
return true;
else
return false;
}
else {
check = false;
return check;
}
}
else{
return false;
}
}

最佳答案

用 try/catch 将该行括起来:

try {
compare = Integer.parseInt(newip[index]);
} catch (NumberFormatException e) {
check = false;
}

然后:

if (check) {
if (compare >= 0 & (compare <= 255)) {
check = true;
} else {
check = false;
}
} else {
return false;
}

关于java - 如何捕获 NumberFormatException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54951888/

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