2301_81526724 2024-04-12 16:43 采纳率: 94.7%
浏览 2
已结题

Java练习简单精编

3、利用接口做参数,写个计算器,能完成加减乘除运算。
(1)定义一个接口 Compute 含有一个方法 int computer(int n, int m)。
(2)设计四个类,分别实现此接口,完成加、減、乘、除运算。
(3)设计一个类 UseCompute,包含方法 public void useCom(Compute com, int one, int two),能够用传递过来的对象调用 computer()方法完成运算,并输出运算的结果。
(4)设计一个主类 Test,调用UseCompute 中的方法 useCom()来完成加减乘除运算。

  • 写回答

3条回答 默认 最新

  • 檀越@新空间 2024-04-16 12:42
    关注

    中午好🌞🌞🌞
    本答案参考ChatGPT-3.5

    问题:如何利用接口做参数,写个计算器,能完成加减乘除运算?

    解决方案:

    1. 定义一个接口 Compute 含有一个方法 int computer(int n, int m)。
    public interface Compute {
        int computer(int n, int m);
    }
    
    1. 设计四个类,分别实现此接口,完成加、减、乘、除运算。
    public class Add implements Compute {
    
        @Override
        public int computer(int n, int m) {
            return n + m;
        }
    
    }
    
    public class Sub implements Compute {
    
        @Override
        public int computer(int n, int m) {
            return n - m;
        }
    
    }
    
    public class Mul implements Compute {
    
        @Override
        public int computer(int n, int m) {
            return n * m;
        }
    
    }
    
    public class Div implements Compute {
    
        @Override
        public int computer(int n, int m) {
            if (m == 0) {
                throw new IllegalArgumentException("除数不能为0");
            }
            return n / m;
        }
    
    }
    
    1. 设计一个类 UseCompute,包含方法 public void useCom(Compute com, int one, int two),能够用传递过来的对象调用 computer() 方法完成运算,并输出运算的结果。
    public class UseCompute {
        public void useCom(Compute com, int one, int two) {
            int result = com.computer(one, two);
            System.out.println(one + " " + com.getClass().getSimpleName() + " " + two + " = " + result);
        }
    }
    
    1. 设计一个主类 Test,调用 UseCompute 中的方法 useCom() 来完成加减乘除运算。
    public class Test {
        public static void main(String[] args) {
            UseCompute useCompute = new UseCompute();
            int a = 10, b = 5;
            Compute add = new Add();
            Compute sub = new Sub();
            Compute mul = new Mul();
            Compute div = new Div();
    
            useCompute.useCom(add, a, b);
            useCompute.useCom(sub, a, b);
            useCompute.useCom(mul, a, b);
            useCompute.useCom(div, a, b);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 4月27日
  • 已采纳回答 4月19日
  • 创建了问题 4月12日