I would like to implement a validation that will accept from a textfield a number(String) and then pass it to a double variable if its Int or double, otherwise a new exception is thrown.
I already implemented a code that is working just for Int numbers. could you give me a hint please?
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;
}
Thank you
Updated:
Thanks everyone for your help. I really appreciate it. The solution that worked for me is:
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;
}