黑马程序员技术交流社区

标题: 检测面向对象的试题。大家都来检测一下你的学习结果吧... [打印本页]

作者: 山西_李帅    时间: 2013-4-10 10:55
标题: 检测面向对象的试题。大家都来检测一下你的学习结果吧...
大家都来检测一下你的学习结果吧,

-测试题.rar

13.83 KB, 阅读权限: 10, 下载次数: 41


作者: 山西_李帅    时间: 2013-4-10 10:59

最后一道关于计算器的完善, 完善除数为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;
        }
}
作者: 我手心里的宝    时间: 2013-4-10 11:03
谢了 下了,看看哈
作者: 胡滨    时间: 2013-4-10 11:03
{:soso_e129:}试试
作者: 王薪婷    时间: 2013-4-10 11:38
谢谢谢谢楼主分享~




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2