最后一道关于计算器的完善, 完善除数为0 的异常
//使用面向对象设计计算器(使用工厂模式)
class Test1
{
public static void main(String[] args){
int a=10;
int b=0;
char c='/';
Operation op=OperationFactory.getInstance(c);
try{
int result=op.oper(a,b);
System.out.println("结果:"+a+c+b+"="+result);
}catch(Exception e){
System.out.println("除数为0");
}
}
}
//运算的接口
interface Operation
{ //计算的方法
int oper(int a,int b) throws Exception;
}
//工厂 根据符号得到一个Operation对象
class OperationFactory
{
public static Operation getInstance(char c){
Operation op=null;
switch(c){
case '+'p=new Add();break;
case '-'p=new Sub();break;
case '*'p=new Mul();break;
case '/'p=new Div();break;
}
return op;
}
}
class Add implements Operation
{
public int oper(int a,int b){
return a+b;
}
}
class Sub implements Operation
{
public int oper(int a,int b){
return a-b;
}
}
class Mul implements Operation
{
public int oper(int a,int b){
return a*b;
}
}
class Div implements Operation
{
public int oper(int a,int b) throws Exception{
if(b==0){
throw new Exception();
}
int result=0;
result=a/b;
return result;
}
} |