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()来完成加减乘除运算。
Java练习简单精编
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
檀越@新空间 2024-04-16 12:42关注中午好🌞🌞🌞
本答案参考ChatGPT-3.5问题:如何利用接口做参数,写个计算器,能完成加减乘除运算?
解决方案:
- 定义一个接口 Compute 含有一个方法 int computer(int n, int m)。
public interface Compute { int computer(int n, int m); }- 设计四个类,分别实现此接口,完成加、减、乘、除运算。
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; } }- 设计一个类 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); } }- 设计一个主类 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); } }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报