使用Java中类,接口,继承等方法编写简单的计算器
- 写个计算器,能完成加减乘除运算
- 定义接⼝做参数
- 加减乘除定义4个类
- 定义⼀个静态⼯具类,把下⾯的接⼝作为其中⼀个形参对象,传递具体的运算符类完成计算
interface ICompute{ int computer(int num1, int num2); }
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e6320d1449840d5bf9191624f66cdeed.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/27d72aba704b8eed718b28280416b010.png#pic_center)
package test.Ex6_9;
public interface Icompute {
int compute(int num1, int num2 );
}
package test.Ex6_9;
public class Addition implements Icompute {
@Override
public int compute(int num1, int num2) {
return num1 + num2;
}
}
package test.Ex6_9;
public class Division implements Icompute{
@Override
public int compute(int num1, int num2) {
try {
return num1 / num2;
}catch (Exception e){
e.printStackTrace();
}
return -1;
}
}
package test.Ex6_9;
public class Multiplication implements Icompute{
@Override
public int compute(int num1, int num2) {
return num1 * num2;
}
}
package test.Ex6_9;
public class Subtraction implements Icompute{
@Override
public int compute(int num1, int num2) {
return num1 - num2;
}
}
在这里插入代码片package test.Ex6_9;
import java.util.Scanner;
public class UserCompute {
public static void compute(Icompute icompute ,int num1 , int num2){
int result = icompute.compute(num1,num2);
System.out.println(result);
}
public static void main(String[] args) {
System.out.println("请输入两个数字(回车键确定)");
Scanner scanner1 =new Scanner(System.in);
int i = scanner1.nextInt();
Scanner scanner2 =new Scanner(System.in);
int j = scanner2.nextInt();
System.out.println("和");
compute(new Addition(),i,j);
System.out.println("差");
compute(new Subtraction(),i,j);
System.out.println("积");
compute(new Multiplication(),i,j);
System.out.println("商");
compute(new Division(),i,j);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7688b3eea7d20d0e9650a5a947cc2561.png)