当前位置:   article > 正文

Java-接口作业练习题2_java中接口的操作题

java中接口的操作题

利用接口做参数,写个计算器,能完成加减乘除运算。 
(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来完成加减乘除运算。

  1. package MIUT;
  2. //定义一个接口Compute含有一个方法int computer(int n, int m)。
  3. public interface Compute {
  4. int computer(int n, int m);
  5. }
  1. package MIUT;
  2. public class Add implements Compute{
  3. @Override
  4. public int computer(int n, int m) {
  5. return n+m;
  6. }
  7. }
  1. package MIUT;
  2. public class Sub implements Compute{
  3. @Override
  4. public int computer(int n, int m) {
  5. return n-m;
  6. }
  7. }
  1. package MIUT;
  2. public class Multiply implements Compute{
  3. @Override
  4. public int computer(int n, int m) {
  5. return n*m;
  6. }
  7. }
  1. package MIUT;
  2. public class Divide implements Compute{
  3. @Override
  4. public int computer(int n, int m) {
  5. if (m!=0)
  6. return n/m;
  7. else {
  8. System.out.println("分母不能为零");
  9. return 0;
  10. }
  11. }
  12. }
  1. package MIUT;
  2. //设计一个类UseCompute,类中含有方法:public void useCom(Compute com, int one, int two),
  3. // 此方法能够用传递过来的对象调用computer方法完成运算,并输出运算的结果。
  4. public class UseCompute {
  5. public void useCom(Compute com, int one, int two) {
  6. System.out.println(com.computer(one,two));
  7. }
  8. }
  1. package MIUT;
  2. import java.util.Scanner;
  3. public class ComputerTest {
  4. public static void main(String[] args) {
  5. int x;
  6. UseCompute a = new UseCompute();
  7. Scanner s = new Scanner(System.in);
  8. System.out.println("请选择想要进行的运算:");
  9. System.out.println("1.加法");
  10. System.out.println("2.减法");
  11. System.out.println("3.乘法");
  12. System.out.println("4.除法");
  13. x = s.nextInt();
  14. if(x==1) {
  15. System.out.println("清输入两个数:");
  16. int n = s.nextInt();
  17. int m = s.nextInt();
  18. a.useCom(new Add(), n, m);
  19. }
  20. if(x==2){
  21. System.out.println("清输入两个数:");
  22. int n = s.nextInt();
  23. int m = s.nextInt();
  24. a.useCom(new Sub(), n, m);
  25. }
  26. if(x==3){
  27. System.out.println("清输入两个数:");
  28. int n = s.nextInt();
  29. int m = s.nextInt();
  30. a.useCom(new Multiply(), n, m);
  31. }
  32. if(x==4){
  33. System.out.println("清输入两个数:");
  34. int n = s.nextInt();
  35. int m = s.nextInt();
  36. a.useCom(new Divide(), n, m);
  37. }
  38. }
  39. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/773044
推荐阅读
相关标签
  

闽ICP备14008679号