【发布时间】:2013-11-30 21:41:26
【问题描述】:
我想实现一个验证,该验证将从文本字段中接受一个数字(字符串),然后将其传递给一个双变量(如果其为 Int 或双精度),否则将引发新异常。
我已经实现了一个仅适用于 Int 数字的代码。请给我一个提示好吗?
protected double validateDiameter() {
try {
if (stringDiameter != null) {
//Checking stringDiameter if its a number by creating a for loop
//that check each character of the string.
//If the string contains only numbers
//the program will continue, if not an exception is thrown.
int lengthofdiameter = stringDiameter.length();
int DiameterCount = 0;
for (int i = 0; i <= lengthofdiameter - 1; i++) {
char t = stringDiameter.charAt(i);
if (Character.isDigit(t)) {
DiameterCount++;
}
}
if (lengthofdiameter == DiameterCount) {
Diameter = Double.parseDouble(stringDiameter);
if (Diameter <= 0 && Diameter >= 9) {
throw new Exception("");
}
} else {
throw new Exception("");
}
}
} catch (Exception e) {
Diameter = 0.0;
JOptionPane.showMessageDialog(null,
"Wrong value on the input area.Please use number." + "\n" + "Check diameter input.",
"Error message!",
JOptionPane.ERROR_MESSAGE);
}
return Diameter;
}
谢谢
更新:
感谢大家的帮助。对此,我真的非常感激。对我有用的解决方案是:
protected double validateDiameter() {
try {
if (stringDiameter != null) {
if (stringDiameter.matches("-?\\d+(\\.\\d+)?")) {
Diameter = Double.parseDouble(stringDiameter);
} else {
throw new Exception("");
}
if (Diameter <= 0 || Diameter > 8) {
throw new Exception("");
}
} else {
throw new Exception("");
}
} catch (Exception e) {
Diameter = 0.0;
JOptionPane.showMessageDialog(null,
"Wrong value on the input area.Please use number." + "\n" +
"Check diameter input.",
"Error message!",
JOptionPane.ERROR_MESSAGE);
}
return Diameter;
}
【问题讨论】:
标签: java swing validation