编程题用代码实现计算器类(Calculator)。 【提示】 编写 Calculator 类。 (1)定义成员变量为运算数1(numberl)和运算数2(number2)。 (2)定义成员方法“加”(add)、“减”(minus)、“乘”(multiple)、“除”(divide (3)定义测试类Test,用计算器类来测试任意两数的加减乘除运算。
时间: 2024-01-20 08:01:52 浏览: 189
下面是Java语言的实现代码:
```java
public class Calculator {
private double number1;
private double number2;
public Calculator(double number1, double number2) {
this.number1 = number1;
this.number2 = number2;
}
public double add() {
return number1 + number2;
}
public double minus() {
return number1 - number2;
}
public double multiple() {
return number1 * number2;
}
public double divide() {
if (number2 == 0) {
throw new ArithmeticException("Divide by zero error");
}
return number1 / number2;
}
}
```
测试类Test:
```java
public class Test {
public static void main(String[] args) {
Calculator calculator = new Calculator(10, 5);
System.out.println("10 + 5 = " + calculator.add());
System.out.println("10 - 5 = " + calculator.minus());
System.out.println("10 * 5 = " + calculator.multiple());
System.out.println("10 / 5 = " + calculator.divide());
}
}
```
阅读全文