gpt4 book ai didi

java - 数字格式异常

转载 作者:行者123 更新时间:2023-12-01 15:17:28 25 4
gpt4 key购买 nike

我正在尝试使用实用函数来获取 int 并检查错误的输入是否会导致
NumberFormat 异常,有没有办法在以下函数中使用非十进制整数

//--- Utility function to get int using a dialog.

public static int getInt(String mess) {
int val;
while (true) { // loop until we get a valid int
String s = JOptionPane.showInputDialog(null, mess);
try {
val = Integer.parseInt(s);
break; // exit loop with valid int
} catch (NumberFormatException nx) {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
}
return val;
}

//end getInt

最佳答案

如果我理解你...也许你可以这样做:

public static int getInt(String mess) {
int val;
while (true) { // loop until we get a valid int
String s = JOptionPane.showInputDialog(null, mess);
try {
if(mess.match("^\d+$")){ // Check if it's only numbers (no comma, no dot, only numeric characters)
val = Integer.parseInt(s); // Check if it's in the range for Integer numbers.
break; // exit loop with valid int
} else {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
} catch (NumberFormatException nx) {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
}
return val;
}

关于java - 数字格式异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11436995/

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