Java面向对象静态方法及域值控制&域值四则运算"以计算器实验为例"(初级)

这篇博客介绍了如何使用Java创建一个简单的计算器类,该类支持用户进行加、减、乘、除操作。当用户按下等号按钮时,计算器根据已输入的数字和选择的运算符计算结果。博主分享了乘除和加减运算的实验代码,这些代码对于初学者理解面向对象编程和逻辑算法很有帮助,为后续实现更复杂的四则混合运算打下基础。
摘要由CSDN通过智能技术生成

*Create a class named Calculator.
A calculator has a method to add digits to a running total.
The user can also press operator keys such as + or * and then enter digits of a second
number.
When the user presses the = button, the calculator computes the result based on the numbers entered so far and the operator chosen. The user can then make further computations.
建立一个名为计算器的组,要求用户可以点击"+", “-”, "", “/” 进行计算,当用户按下”=“ 按钮时,计算结果会显示在输入栏里。
图片示例:
在这里插入图片描述
对于刚刚完成对象静态方法的同学来说, 实现四则混合运算,实现可执行文件面还是有些困难。此博暂时只针对 乘除 / 加减 运算,并由内置代码实现。但其中对于结果的处理计算与显示,还是有许多值得学习的地方。
实验代码1(乘除实验):

public class _CalculatorExperiment {
   
    public static void main(String[] args) {
   
    	_Calculator calc = new _Calculator();
        calc.addDigit(1);
        calc.setOperator("*");
        calc.addDigit(6);
        calc.setOperator("/");
        calc.addDigit(2);
        double result = calc.compute();
        //将double类型进行判别,判断是否需要输出double类型
        if (result%(int)result==0) {
   
        //整数判别
        	System.out.println(calc);

            System.out.println("result = " + (int)result);
        }else {
   
        System.out.println(calc);

        System.out.println("result = " + result);	}
    }
}

实验结果1(乘除实验):
在这里插入图片描述
实验代码2(加减实验):

public class _CalculatorExperiment {
   
    public static void main(String[] args) {
   
    	_Calculator calc = new _Calculator();
        calc.addDigit(1);
        calc.setOperator("+");
        calc.addDigit(
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值