以下是基于你提供的代码实现的 Calculator 类:
public class Calculator {
private double currentValue = 0.0;
public double opAdd(double operand) {
currentValue += operand;
return currentValue;
}
public double opSubtract(double operand) {
currentValue -= operand;
return currentValue;
}
public double opMultiply(double operand) {
currentValue *= operand;
return currentValue;
}
public double opDivide(double operand) throws ArithmeticException {
if (operand == 0.0) {
throw new ArithmeticException("Division by zero");
}
currentValue /= operand;
return currentValue;
}
}
这个类包含了四种基本运算:加、减、乘和除。每种运算都接受一个参数,并将其与当前值进行计算,然后返回新的结果。如果执行除法时遇到分母为零的情况,则会抛出异常。
在 CalculatorGUI 类中,我们使用 Calculator 类的对象来执行实际的计算。根据用户按下哪个按钮,我们调用相应的方法,并将当前答案存储在 currentValue 变量中。




