package com.dahua.caculator;
/**
* Created by walle
* 2017/10/11.14:46
* good good study!
*/
public class Operation {
private double numberA;
private double numberB;
public double getNumberA() {
return numberA;
}
public void setNumberA(double numberA) {
this.numberA = numberA;
}
public double getNumberB() {
return numberB;
}
public void setNumberB(double numberB) {
this.numberB = numberB;
}
public double getResult() {
double result = 0;
return result;
}
}
子类加法计算类
package com.dahua.caculator;
/**
* Created by walle
* 2017/10/11.14:50
* good good study!
*/
public class OperationAdd extends Operation {
@Override
public double getResult() {
double result = 0;
result = getNumberA()+getNumberB();
return result;
}
}
子类除法计算类
/**
* Created by walle
* 2017/10/11.15:26
* good good study!
*/
public class OperationDiv extends Operation {
@Override
public double getResult() {
double result =0;
if(getNumberB()==0){
throw new RuntimeException("除数不能为0");
}
result = getNumberA()/getNumberB();
return result;
}
}
其他计算类自己写吧
工厂类 根据提供的运算符决定调用哪个计算类
package com.dahua.caculator;
/**
* Created by walle
* 2017/10/11.14:52
* good good study!
*/
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 OperationDiv();
break;
}
return operation;
}
}
运行计算的方法
importjava.util.Scanner;
/**
* Created by walle
* 2017/10/11.15:00
* good good study!
*/
public class Caculator {
public static void main(String[] args) {
Operation operation;
Scanner scanner = new Scanner(System.in);
String operate = scanner.next();
System.out.println("您输入的运算符是:"+operate);
operation = OperationFactory.createOperate(operate);
Double numberA = scanner.nextDouble();
System.out.println("您输入的第一个数字是:"+numberA);
Double numberB = scanner.nextDouble();
System.out.println("您输入的第二个数字是:"+numberB);
operation.setNumberA(numberA);
operation.setNumberB(numberB);
double result = operation.getResult();
System.out.println("输出结果是:"+result);
}
}
package com.dahua.caculator;/** * Created by 张向吉 * 2017/10/11.14:46 * good good study! */public class Operation { private double numberA; private double numberB; public double getN