package com.guoxiaoming.cal;
public abstract class Operation {
private double num1;
private double num2;
public double getNum1(){
return num1;
}
public double getNum2(){
return num2;
}
public void setNum1(double num1){
this.num1 = num1;
}
public void setNum2(double num2){
this.num2 = num2;
}
public abstract double getResult();
}
package com.guoxiaoming.cal;
public class AddOperation extends Operation{
@Override
public double getResult() {
double result = this.getNum1()+this.getNum2();
return result;
}
}
package com.guoxiaoming.cal;
public class SubOperation extends Operation{
@Override
public double getResult() {
double result = this.getNum1() - this.getNum2();
return result;
}
}
package com.guoxiaoming.cal;
public class OperationFactory {
public static Operation getOperation(String oper){
if(oper.equals("+")){
return new AddOperation();
}else if(oper.equals("-")){
return new SubOperation();
}
return null;
}
}
package com.guoxiaoming.cal;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]){
System.out.println("---计算器程序---");
Scanner sc = new Scanner(System.in);
System.out.println("输入第一个操作数:");
String strNum1 = sc.nextLine();
System.out.println("请输入操作符:");
String oper = sc.nextLine();
System.out.println("请输入第二个操作数:");
String strNum2 = sc.nextLine();
double result = 0;
double num1 = Double.parseDouble(strNum1);
double num2 = Double.parseDouble(strNum2);
Operation operation = OperationFactory.getOperation(oper);
operation.setNum1(num1);
operation.setNum2(num2);
result = operation.getResult();
System.out.println(result);
}
}