1

I am creating a Java swing calculator. I want to get the reciprocal of a given number. So if I input 0, it should print out an error message.

Here's my code:

public class Calculator extends JFrame implements ActionListener {
    double num=0, num2=0;
    String operator;
    JButton bReciprocal=new JButton("1/x");
    JTextField result=new JTextField("0", 25);

    public void actionPerformed(ActionEvent e) {
        String command=e.getActionCommand();
        if(command=="1/x") {
            try {
                num=1/num;
                result.setText(Double.toString(num));
            }
            catch(ArithmeticException ae) {
                result.setText("Math Error");
                num=0;
            }
        }
    }
}

However, if I give 0 as the input, what I get is infinity. What's wrong with this code? How can I make it show "Math error" instead of infinity?

Eran
  • 387,369
  • 54
  • 702
  • 768
sam_rox
  • 739
  • 3
  • 14
  • 29
  • 1
    `command=="1/x"` is not how `String` comparison in Java works, see [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – MadProgrammer Oct 20 '14 at 05:17
  • Have a look at this http://stackoverflow.com/questions/14137989/java-division-by-zero-doesnt-throw-an-arithmeticexception-why – Sivakumar Oct 20 '14 at 05:22

2 Answers2

2

1.0/0.0 (division of doubles) returns infinity.

You can even see that the definition of POSITIVE_INFINITY in the Double and Float classes is :

/**
 * A constant holding the positive infinity of type
 * <code>double</code>. It is equal to the value returned by
 * <code>Double.longBitsToDouble(0x7ff0000000000000L)</code>.
 */
public static final double POSITIVE_INFINITY = 1.0 / 0.0;

/**
 * A constant holding the positive infinity of type
 * <code>float</code>. It is equal to the value returned by
 * <code>Float.intBitsToFloat(0x7f800000)</code>.
 */
public static final float POSITIVE_INFINITY = 1.0f / 0.0f;

If you want an ArithmeticException to be thrown, divide integers : 1/0.

Therefore, if you are working with doubles, you don't need to catch that exception. Just add a check that num != 0.0.

BTW, you should change if(command=="1/x") to if(command.equals("1/x")).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • So if working with doubles division by zero results in infinity. Exception would occur only if the value is declared as integer? – sam_rox Oct 20 '14 at 05:37
  • @sam_rox Exception would occur if both the divisor and the dividend are int/long and the divisor is 0. – Eran Oct 20 '14 at 05:40
  • 1
    :This is what I did.And it works finr.Just want to knoew if this is what you told I should do `if(command.equals("1/x")){ if(num==0){ result.setText("Math Error"); } else{ num=1/num; result.setText(Double.toString(num)); } }` – sam_rox Oct 20 '14 at 05:50
  • @Eran :Thanks for the answer – sam_rox Oct 20 '14 at 05:54
1

Since IEEE standard for integer arithmetic did not define Integer.NaN unlike float or double, you need to throw an error when dealing with input of 0 or less

if (num <= 0) {
 throw new IllegalArgumentException("Input number is is 0");
}

Also, you need to compare Strings properly using equals like if(command.equals("1/x"))

Piyush Mattoo
  • 15,454
  • 6
  • 47
  • 56
  • In my other buttons like addition,subtraction I have written as `if(command=="-")` .Should these too need to be changes to `command.equals("-")` likewise. Even with `(command=="-")` the calculations do get performed.Why is that – sam_rox Oct 20 '14 at 05:53
  • @sam_rox: == operator compares the object reference however string literals return true when compared to each other using == operator as they point to the same Object – Piyush Mattoo Oct 20 '14 at 05:57
  • So should I change these to `equals()` or is it okay to keep it this way – sam_rox Oct 20 '14 at 06:22
  • Change to equals for sure – Piyush Mattoo Oct 20 '14 at 16:06