*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(