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!");
}
}
}
但這種方式仍然寫我「無限」的文本字段。有人可以建議我錯在哪裏嗎?
謝謝你的回答,但我該如何解決我的問題?我將異常改爲算術,但顯然仍然有相同的結果。 – vehk
做分割前檢查零值,並刪除你的'try catch' – LoganMzz
那麼,這是很大的幫助,謝謝你的時間:) – vehk