ZBLOG

请你根据这段代码帮我写好Calculator类,其中有四个方法:opAdd等,他们都只能接受一个参数.代码如下:import javax.swing.; import java.awt.; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class CalculatorGUI implements ActionListener { // Buttons and a place ...

以下是基于你提供的代码实现的 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 变量中。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=4476

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?