我正在創建一個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
?
'command ==「1/x」'是不是如何在Java中的字符串比較工作,請參閱[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – MadProgrammer 2014-10-20 05:17:26
看看這個http:// stackoverflo w.com/questions/14137989/java-division-by-zero-doesnt-throw-an-arithmeticexception-wr – Sivakumar 2014-10-20 05:22:24