Hamdysaad20
Hamdysaad20

Reputation: 21

Java FX arithmetic expression in a button

hi i want to do a button that takes two input fields and trying to do the following :

  1. chick if it's a number .(so it can devide the two numbers)
  2. 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

Upvotes: 0

Views: 109

Answers (1)

James_D
James_D

Reputation: 209684

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 {
        
    }

});

Upvotes: 3

Related Questions