¢编写一个计算器,完成+-*/ 运算 ¢ (1)定义一个接口Compute含有一个方法 int computer(int a,int b); (2)设计四个类分别实现此接口,完成+-*/运算 (3)设计一个测试类,完成+-*/运算,输出如下运行结果:
时间: 2023-06-16 09:05:16 浏览: 247
以下是 Java 代码实现:
```java
// 计算器接口
interface Compute {
int compute(int a, int b);
}
// 加法类
class Add implements Compute {
public int compute(int a, int b) {
return a + b;
}
}
// 减法类
class Subtract implements Compute {
public int compute(int a, int b) {
return a - b;
}
}
// 乘法类
class Multiply implements Compute {
public int compute(int a, int b) {
return a * b;
}
}
// 除法类
class Divide implements Compute {
public int compute(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("除数不能为 0!");
}
return a / b;
}
}
// 测试类
public class Calculator {
public static void main(String[] args) {
Compute add = new Add();
Compute subtract = new Subtract();
Compute multiply = new Multiply();
Compute divide = new Divide();
int a = 10, b = 5;
System.out.println(a + " + " + b + " = " + add.compute(a, b));
System.out.println(a + " - " + b + " = " + subtract.compute(a, b));
System.out.println(a + " * " + b + " = " + multiply.compute(a, b));
System.out.println(a + " / " + b + " = " + divide.compute(a, b));
}
}
```
输出结果:
```
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2
```
阅读全文