继承和多态
import java.util.Scanner;
class operationFc {
String operator;
public operationFc(String opt) {
operator = opt;
}
public operation creatOperator(double a, double b) {
operation op = null;
switch(operator) {
case "+" :
op = new operationAdd(a, b);
break;
case "-" :
op = new operationSub(a, b);
break;
case "*" :
op = new operationMul(a, b);
break;
case "/" :
op = new operationDiv(a, b);
break;
}
return op;
}
}
public abstract class operation {
protected double A;
protected double B;
public operation(double a, double b) {
this.A = a;
this.B = b;
}
public abstract double GetResult();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入数字A");
String A = sc.nextLine();
double a = Double.parseDouble(A);
System.out.println("请选择运算符号(+、-、*、/):");
String B = sc.nextLine();
System.out.println("请输入数字B:");
String C = sc.nextLine();
double c = Double.parseDouble(C);
operationFc p = new operationFc(B);
operation prtn = p.creatOperator(a, c);
System.out.println("结果是 " + prtn.GetResult());
}
}
class operationAdd extends operation {
public operationAdd(double a, double b) {
super(a, b);
}
public double GetResult() {
return A + B;
}
}
class operationSub extends operation {
public operationSub(double a, double b) {
super(a, b);
}
public double GetResult() {
return A - B;
}
}
class operationMul extends operation {
public operationMul(double a, double b) {
super(a, b);
}
public double GetResult() {
return A * B;
}
}
class operationDiv extends operation {
public operationDiv(double a, double b) {
super(a, b);
}
public double GetResult() {
if (B == 0)
throw new ArithmeticException("输入出错,除数不能为零!");
else
return A / B;
}
}