我想实现一个验证,它将接受来自textfield的数字(String),然后将其传递给double变量(如果是Int或double),否则抛出新的异常。
我已经实现了一个仅适用于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;
}
答案 0 :(得分:2)
我的是stringDiameter;基本上首先你尝试将输入解析为Integer;如果这不起作用你可以尝试加倍,如果这仍然不起作用,它意味着没有一个
String s = "10.2";
try {
int i = Integer.parseInt(s);
//int routine
System.out.println(i);
} catch (NumberFormatException e) {
if (s.matches("-?\\d+(\\.\\d+)?")) {
double d = Double.parseDouble(s);
//double routine
System.out.println(d);
} else {
// "Wrong value on the input area.Please use number." + "\n" + "Check //diameter input.", "Error message!",
System.out.println("Wrong");
throw new IllegalArgumentException();
}
}
答案 1 :(得分:1)
boolean isDouble(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
boolean isInteger(String s) {
try {
Integer.parseInt(s);
return true;
} catch(NumberFormatException e) {
return false;
}
}
我必须承认我有点困惑你真正想要的东西。上面的代码检查给定的字符串是否为double,是您要查找的内容?
答案 2 :(得分:1)
Ben和user1121883的答案均使用异常处理。如果在不使用异常的情况下需要解决方案(在检查时),那么我建议您在这里查看这些答案(以及以下答案):