1.小王正在编写一个简单的计算器程序,要求输入两个整数和运算符号(加、减、乘、除),输出计算结果。小王用面向过程方法编写了下面的代码。请采用面向对象方法通过恰当的设计模式对小王的代码进行重构。
int main()
{
int numa,numb; char oper; double result;
cin>>numa>>numb; cin>>oper;
switch(oper) {
case '+': result=numa+numb; break;
case '-': result=numa-numb; break;
case '*': result=numa*numb; break;
case '/': result=numa/(double)numb; break;
}
cout<<result<<endl;
return 0;
}
代码设计:
基类:
public abstract class Operate {
abstract double oper(double a,double b);
}
子类:
public class Add extends Operate{
@Override
double oper(double a, double b) {
// TODO Auto-generated method stub
return (a+b);
}
}
public class Sub extends Operate{
@Override
double oper(double a, double b) {
// TODO Auto-generated method stub
return (a-b);
}
}
public class Div extends Operate {
@Override
double oper(double a, double b) {
// TODO Auto-generated method stub
return (a/b);
}
}
public class Mul extends Operate {
@Override
double oper(double a, double b) {
// TODO Auto-generated method stub
return (a*b);
}
}
函数及测试代码:
import java.util.Scanner;
public class Test {
Operate creat_op(String c) {
Operate op=null;
if(c.equals("+"))
op=new Add();
else if(c.equals("-"))
op=new Sub();
else if(c.equals("/"))
op=new Div();
else if(c.equals("*"))
op=new Mul();
else {
System.out.println("null");
}
return op;
}
double make_op(Operate op,double a,double b) {
double result = 0;
if(op.equals(null)) {
System.out.println("error");
}
else {
result=op.oper(a, b);
}
return result;
}
@SuppressWarnings("resource")
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("Please input a");
double a=sc.nextDouble();
System.out.println("Please input b");
double b=sc.nextDouble();
System.out.println("Please input op");
sc.nextLine();
String c=sc.nextLine();
Test test=new Test();
double result=test.make_op(test.creat_op(c), a, b);
System.out.print("Result is :"+result);
}
}