java基础练习题8

该文描述了一个使用Java编程实现的简单计算器系统,通过定义一个Computer接口,以及Add、Sub、Mul、Div四个实现了该接口的类,分别对应加、减、乘、除四种运算。UseComputer类用于调用这些运算类的方法并输出结果。在Test类的主方法中,用户可以输入两个数进行四种运算。
摘要由CSDN通过智能技术生成
  1. 利用接口做参数,写个计算器,能完成+-*/运算

(1)定义一个接口Computer含有一个方法    int computer(int x,int y);

(2)设计四个类(Add、Sub、Mul、Div)分别实现此接口,完成+-*/运算

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

      public void useCom(Computer com, int m, int n)

     此方法要求能够:

           1)用传递过来的对象调用computer方法完成运算

           2)输出运算的结果

(4)设计一个测试类Test,调用UseComputer中的方法useCom来完成+-*/运算

在主方法中要包含以下代码:

 UseComputer use=new UseComputer();

 use.useCom(new Add(), m, n);

接口Computer1

public interface Computer1 {
    int computer(int ,int y);
}

Add类

    class Add implements Computer1{
        public int computer(int x, int y) {
            return x+y;
        }
    }

Sub类

public class Sub implements Computer1{
    public int computer(int x, int y) {
        return x-y;
    }
}

Mul类

public class Mul implements Computer1 {
    public int computer(int x, int y) {
        return x * y;
    }
}

Div类

public class Div implements Computer1{
    public int computer(int x, int y) {
        if(y==0){
            System.out.println("分母不能为0");
            System.exit(0);
        }
        return x/y;       
    }
}

UseComputer类

public class UseComputer{
    public static void useCom(Computer1 com,int x,int y){
        System.out.println(com.computer(x,y));
    }
}

Test类

import java.util.Scanner;

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

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值