- 利用接口做参数,写个计算器,能完成+-*/运算
(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);
}
}