Issue
hi i want to do a button that takes two input fields and trying to do the following :
- chick if it's a number .(so it can devide the two numbers)
- i can't devide any number by zero . and showing that it's a arithmetic expression . so any help ? the code is blow :: enter image description here
code ::
b4.setOnMouseClicked((MouseEvent ex) -> {
String Num1 = tf4.getText();
String Num2 = tf8.getText();
if(Num1.matches("^\\d+(\\.\\d+)?") && Num2.matches("^\\d+(\\.\\d+)?")) {
try {
double Num1f = Double.parseDouble(Num1);
double Num2f = Double.parseDouble(Num2);
double result =(Num2f / Num1f);
valf4.setText(String.valueOf(result));
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException");
valf4.setText("You can't do that !");
}
} else {
}
});
and it show infinity not what i expected as i did in catch area
Solution
Floating point arithmetic in Java does not throw exceptions for division by zero; it evaluates to one of the special values in the Double
class (Double.POSITIVE_INFINITY
or Double.NEGATIVE_INFINITY
).
Instead of catching the exception, you can just test if the denominator is zero, or test if the result is infinite:
b4.setOnMouseClicked((MouseEvent ex) -> {
String num1 = tf4.getText();
String num2 = tf8.getText();
if(num1.matches("^\\d+(\\.\\d+)?") && num2.matches("^\\d+(\\.\\d+)?")) {
double num1f = Double.parseDouble(num1);
double num2f = Double.parseDouble(num2);
double result = num2f / num1f;
if (Double.isInfinite(result)) {
valf4.setText("You can't do that !");
} else {
valf4.setText(String.valueOf(result));
}
} else {
}
});
Answered By - James_D
Answer Checked By - Marilyn (JavaFixing Volunteer)