利用接口做参数,写个计算器,能完成加减乘除运算。 定义一个接口icompute含有一个方法int computer(int n, int m)。 定义add类实现接口icompute,实现computer方法,求m,n之和 定义sub类实现接口icompute,实现computer方法,求n-m之差 定义main类,在里面输入两个整数a, b,利用add类和sub类的computer方法,求第一个数a和第二个数b之和,输出和,第一个数a和第二个数b之差,输出差。
时间: 2023-05-31 22:18:48 浏览: 115
### 回答1:
利用接口做参数,写一个计算器,能完成加减乘除运算。首先定义一个接口icompute,其中包含一个方法int computer(int n, int m)。然后定义add类实现接口icompute,实现computer方法,求m,n之和;定义sub类实现接口icompute,实现computer方法,求n-m之差。最后在main类中输入两个整数a, b,利用add类和sub类的computer方法,求第一个数a和第二个数b之和,输出和,第一个数a和第二个数b之差,输出差。
### 回答2:
利用接口做参数,实现一个计算器可以完成加减乘除运算,可以通过定义接口icompute和实现add类和sub类来实现。具体实现步骤如下:
1.定义接口icompute,包含一个方法int computer(int n, int m)。
2.定义add类实现接口icompute,实现computer方法,计算m和n之和。
3.定义sub类实现接口icompute,实现computer方法,计算n-m之差。
4.定义main类,在里面输入两个整数a和b,使用add类和sub类的computer方法,分别求第一个数a和第二个数b的和和差,并输出结果。
完整代码如下:
```java
//定义接口icompute,包含一个方法int computer(int n, int m)
interface icompute {
int computer(int n, int m);
}
//定义add类实现接口icompute,计算n和m之和
class add implements icompute{
public int computer(int n, int m){
return n + m;
}
}
//定义sub类实现接口icompute,计算n和m之差
class sub implements icompute{
public int computer(int n, int m){
return n - m;
}
}
//定义main类,输入两个整数a和b,使用add类和sub类的computer方法,分别求第一个数a和第二个数b的和和差,并输出结果
public class Calculator {
public static void main(String[] args){
int a = 10;
int b = 5;
//使用add类的computer方法,求a和b的和,并输出
add adder = new add();
int result_add = adder.computer(a,b);
System.out.println(a + " + " + b + " = " + result_add);
//使用sub类的computer方法,求a和b的差,并输出
sub suber = new sub();
int result_sub = suber.computer(a,b);
System.out.println(a + " - " + b + " = " + result_sub);
}
}
```
运行结果如下:
```
10 + 5 = 15
10 - 5 = 5
```
这样,就使用接口和类来实现了一个简单的计算器,可以进行加减乘除运算。其中,add类和sub类分别实现了icompute接口,分别用于计算两个数的和和差。在main类中,分别调用了add类和sub类的computer方法,求出a和b的和和差,并输出结果。
### 回答3:
计算器是一个常见的工具,通过计算器可以方便快捷地完成加减乘除等计算操作。而通过接口做参数的方式设计计算器,则可以更好地实现模块化和扩展性。
首先,需要定义一个icompute接口,含有一个抽象方法computer,方法需要传入两个整型参数n和m,并返回一个整型结果,表示进行计算后的运算结果。
接着,需要定义add类和sub类,这两个类都要实现icompute接口,并分别实现计算加法和减法的方法。
在main类中,首先需要输入两个整型数a和b,然后利用add类的computer方法计算a+b的和,并输出结果。接着利用sub类的computer方法计算a-b的差,并输出结果。
可以通过以下代码实现:
interface ICompute {
int computer(int n, int m);
}
class Add implements ICompute {
public int computer(int n, int m) {
return n + m;
}
}
class Sub implements ICompute {
public int computer(int n, int m) {
return n - m;
}
}
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 5;
Add add = new Add();
int sum = add.computer(a, b);
System.out.println("a + b = " + sum);
Sub sub = new Sub();
int diff = sub.computer(a, b);
System.out.println("a - b = " + diff);
}
}
上述代码使用了接口和抽象方法的概念,将计算加法和减法的方法进行了抽象和分离。通过将实现了icompute接口的类传入主函数中,并调用其computer方法实现计算器功能。
当需要添加新的计算功能时,只需要新建一个类,并实现icompute接口即可,不需要修改已有的代码,方便扩展。
利用接口做参数,编写计算器,实现了加减乘除等运算,并且具有灵活的扩展性,可以更好地满足实际应用的需求。