利用接口做参数,写个计算器,能完成加减乘除运算

利用接口做参数,写个计算器,能完成加减乘除运算。

(1)定义一个接口IComputer含有一个抽象方法int computer(int one, int two),其中参数one和two分别为参与运算的操作数1和操作数2(按先后顺序)。

(2)设计四个类Add类、Sub类、Mul类、Div类,分别实现IComputer接口,完成加、减、乘、除运算。 

(3)设计一个类UseComputer,类中含有方法:

public static void useCom(IComputer com, int one, int two)

此方法能够通过传递过来的IComputer的对象com调用computer方法完成某种运算,并输出运算的结果,其中参数one和two分别为参与运算的操作数1和操作数2。

另外,上述useCom方法中请进行如下处理:若进行除法运算,出现除数为零时,请输出下列提示"Divide by zero, meaningless",可以通过判断条件“com instanceof Div && two==0”为真时,进行上述处理。  //暂时还没研究出来如何进行此步操作

(4)调用UseComputer中的方法useCom来完成一组键盘输入数据的加减乘除运算。

import java.util.Scanner;
interface IComputer{
     int computer(int one,int two);
}
class Add implements IComputer{
     public int computer(int one, int two) {
          return one+two;
     }
}
class Sub implements IComputer{
     public int computer(int one, int two) {
          return one-two;
     }
}
class Mul implements IComputer{
     public int computer(int one, int two) {
          return one*two;
     }
}
class Div implements IComputer{
     public int computer(int one, int two) {
          if(two==0){
               System.out.println("Divide by zero, meaningless");
               System.exit(0);
          }
          return one/two;       //若类型为short、int、long,除数为0会报错
     }
}
class UseComputer{
     public static void useCom(IComputer com,int one,int two){
          System.out.println(com.computer(one,two));
     }
}

public class Test {
     public static void main(String args[]) {
          Scanner sc=new Scanner(System.in);
          int a=sc.nextInt();
          int b=sc.nextInt();
          UseComputer.useCom(new Add(),a,b);
          UseComputer.useCom(new Sub(),a,b);
          UseComputer.useCom(new Mul(),a,b);
          UseComputer.useCom(new Div(),a,b);
     }
}

说明:

(1)输入共一行,包含2个整型数字(分隔符为空格),这两个数字作为参与加减乘除运算的操作数。

(2)输出时每个运算结果占一行。

输入格式:

10 2

输出格式:

12

8

20

5

输入样例:

2 0

输出样例:

2

2

0

Divide by zero, meaningless

运行结果:

 

 

 

  • 11
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值