2014-10-20 26 views
1

我正在創建一個Java swing計算器。我想得到給定數字的倒數。所以如果我輸入0,它應該打印出一條錯誤信息。獲得Java中的數字例外的倒數

這裏是我的代碼:

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

但是,如果我給0作爲輸入,我得到的是infinity。這段代碼有什麼問題?我如何讓它顯示「數學錯誤」而不是infinity

+1

'command ==「1/x」'是不是如何在Java中的字符串比較工作,請參閱[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – MadProgrammer 2014-10-20 05:17:26

+0

看看這個http:// stackoverflo w.com/questions/14137989/java-division-by-zero-doesnt-throw-an-arithmeticexception-wr – Sivakumar 2014-10-20 05:22:24

回答

2

1.0/0.0(雙倍分割)返回無窮大。

你甚至可以看到,在雙倍的POSITIVE_INFINITY定義和Float類是:

/** 
* 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; 

如果你想要一個ArithmeticException被拋出,除整數:1/0。

因此,如果您正在使用雙打,則無需捕獲該異常。只需添加一個支票,即num != 0.0

順便說一句,你應該改變if(command=="1/x")if(command.equals("1/x"))

+0

因此,如果使用零加倍除數將導致無窮大。只有在將值聲明爲整數時纔會出現異常? – 2014-10-20 05:37:27

+0

@sam_rox如果除數和除數都是int/long且除數爲0,則會發生異常。 – Eran 2014-10-20 05:40:57

+1

:這就是我所做的。它的工作原理。只是想知道,如果這是你告訴我應該做的'如果(command.equals( 「1/X」)){ \t \t \t如果(NUM == 0){ \t \t \t \t result.setText( 「數學錯誤」); \t \t \t} \t \t \t否則{ \t \t \t \t NUM = 1/NUM; \t \t \t \t result.setText(Double.toString(num)); \t \t \t} \t \t}' – 2014-10-20 05:50:15

0

由於對整數運算IEEE標準沒有定義Integer.NaN不像floatdouble,你或小於0

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

而且輸入打交道時,需要拋出一個錯誤,你需要正確compare Strings使用equals like if(command.equals("1/x"))

+0

在我的其他按鈕中,比如加法,減法,我寫成了'if(command ==「 - 」)「。它們也需要修改爲'command.equals(」 - 「)'同樣。即使用'(command ==「 - 」)'計算確實得到了執行。爲什麼 – 2014-10-20 05:53:50

+0

@sam_rox:==運算符會比較對象引用,但是字符串文字在使用==運算符時相互比較時會返回true,因爲它們指向同樣的對象 – 2014-10-20 05:57:43

+0

所以我應該把它們改爲'equals()'還是可以保持這種方式 – 2014-10-20 06:22:45