尝试通过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!");
}
}
}
但是这样它仍然在文本字段中写了“Infinity”。有人可以建议我哪里错了吗?
答案 0 :(得分:0)
使用double
时,零分区返回Double.POSITIVE_INFINITY
或Double.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
。