JAVA 3.编程实现运算类—工厂设计模式 【问题描述】 (1)定义抽象类Operation,有double型数据成员numberA、numberB,有抽象方法getResult() (2)定义Operation的4个子类,分别实现加、减、除运算,二个数的平均数运算 (3)定义类OperationFactory:有静态方法Operation createOperate(String operate); 根据形参operate的值创建相应加、减、除、平均值类的对象,赋给抽象类引用后返回 (4)定义测试类及主方法:用户从键盘输入运算数及运算符,根据运算符调用OperationFactory类的静态方法,创建相应实例,设置运算数,输出运行结果 【输入形式】 一个表达式(数据与运算符之间空格间隔) 【输出形式】 表达式运算的结果,保留3位小数 【样例输入】 表4.3实验题目3测试用例 序号 样例输入 样例输出 1 45.8 + 80.9 Result:126.700 2 100 / 3 Result:33.333 3 123 / 0 Devide by zero!
时间: 2024-01-21 15:19:38 浏览: 81
以下是Java代码实现:
(1)Operation抽象类
```java
public abstract class Operation {
protected double numberA;
protected double numberB;
public abstract double getResult();
}
```
(2)Operation子类
```java
public class OperationAdd extends Operation {
public double getResult() {
return numberA + numberB;
}
}
public class OperationSub extends Operation {
public double getResult() {
return numberA - numberB;
}
}
public class OperationMul extends Operation {
public double getResult() {
return numberA * numberB;
}
}
public class OperationDiv extends Operation {
public double getResult() {
if (numberB == 0) {
throw new IllegalArgumentException("Devide by zero!");
}
return numberA / numberB;
}
}
public class OperationAvg extends Operation {
public double getResult() {
return (numberA + numberB) / 2;
}
}
```
(3)OperationFactory类
```java
public class OperationFactory {
public static Operation createOperate(String operate) {
Operation operation = null;
switch (operate) {
case "+":
operation = new OperationAdd();
break;
case "-":
operation = new OperationSub();
break;
case "*":
operation = new OperationMul();
break;
case "/":
operation = new OperationDiv();
break;
case "avg":
operation = new OperationAvg();
break;
default:
throw new IllegalArgumentException("Invalid operator!");
}
return operation;
}
}
```
(4)测试类
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入表达式:");
double numberA = scanner.nextDouble();
String operator = scanner.next();
double numberB = scanner.nextDouble();
Operation operation = OperationFactory.createOperate(operator);
operation.numberA = numberA;
operation.numberB = numberB;
double result = operation.getResult();
System.out.printf("Result:%.3f", result);
}
}
```
注意:以上代码需要在同一个包中,并且运行时需要手动输入数据和运算符。
阅读全文