2015-10-13 63 views
1

試圖通過零異常在我的計算器項目通過try/catch塊加分:例外處理的麻煩

private class Calculate implements ActionListener { 

     public void actionPerformed(ActionEvent e) { 
      try { 
       if (operation.equals("/")) { 
        display.setText(Double.toString(getResult()/Double.parseDouble(display.getText()))); 
        setResult(Double.parseDouble(display.getText())); 
       } 
       else if (operation.equals("*")) { 
         display.setText(Double.toString(getResult() * Double.parseDouble(display.getText()))); 
         setResult(Double.parseDouble(display.getText())); 
       } 
       else if (operation.equals("-")) { 
        display.setText(Double.toString(getResult() - Double.parseDouble(display.getText()))); 
         setResult(Double.parseDouble(display.getText())); 
       } 
       else if (operation.equals("+")) { 
         display.setText(Double.toString(getResult() + Double.parseDouble(display.getText()))); 
         setResult(Double.parseDouble(display.getText())); 
       } 
       if (display.getText().endsWith(".0")) { 
        display.setText(display.getText().replace(".0", "")); 
       } 
       calculationMade = true; 
       operation = ""; 
      } 
      catch (IllegalArgumentException exc) { 
       display.setText("You cannot divide by zero!"); 
      } 
     } 
    } 

但這種方式仍然寫我「無限」的文本字段。有人可以建議我錯在哪裏嗎?

回答

0

double工作,除數爲零Double.POSITIVE_INFINITYDouble.NEGATIVE_INFINITY(取決於操作數的標誌)

System.out.println(1.0d/0d); 
System.out.println(-1.0d/0d); 
System.out.println(1.0d/-0d); 
System.out.println(-1.0d/-0d); 

只有非十進制運算拋出零分裂異常返回。並且例外不是IllegalArgumentException而是ArithmeticException

+0

謝謝你的回答,但我該如何解決我的問題?我將異常改爲算術,但顯然仍然有相同的結果。 – vehk

+0

做分割前檢查零值,並刪除你的'try catch' – LoganMzz

+0

那麼,這是很大的幫助,謝謝你的時間:) – vehk