编写一个JAVA程序,完成以下任务:(1)创建一个用于数学运算的接口,创建这个数学运算接口的四个实现:算术运算加、减、乘、除,这四个算术运算要实现它们的相应算术运算;(2)编写一个测试类进行运行测试。
时间: 2024-05-16 21:18:06 浏览: 80
以下是JAVA程序的实现:
MathOperation.java
```java
public interface MathOperation {
double operate(double a, double b);
}
```
Addition.java
```java
public class Addition implements MathOperation {
@Override
public double operate(double a, double b) {
return a + b;
}
}
```
Subtraction.java
```java
public class Subtraction implements MathOperation {
@Override
public double operate(double a, double b) {
return a - b;
}
}
```
Multiplication.java
```java
public class Multiplication implements MathOperation {
@Override
public double operate(double a, double b) {
return a * b;
}
}
```
Division.java
```java
public class Division implements MathOperation {
@Override
public double operate(double a, double b) {
if (b == 0) {
throw new ArithmeticException("Division by zero!");
}
return a / b;
}
}
```
TestMathOperation.java
```java
public class TestMathOperation {
public static void main(String[] args) {
MathOperation addition = new Addition();
System.out.println("2 + 3 = " + addition.operate(2, 3));
MathOperation subtraction = new Subtraction();
System.out.println("5 - 3 = " + subtraction.operate(5, 3));
MathOperation multiplication = new Multiplication();
System.out.println("2 * 3 = " + multiplication.operate(2, 3));
MathOperation division = new Division();
try {
System.out.println("6 / 2 = " + division.operate(6, 2));
System.out.println("6 / 0 = " + division.operate(6, 0));
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
```
运行以上程序,输出结果如下:
```
2 + 3 = 5.0
5 - 3 = 2.0
2 * 3 = 6.0
6 / 2 = 3.0
Division by zero!
```
阅读全文