用JAVA编写一个支持加减乘除取余运算的窗口
时间: 2024-11-05 08:34:43 浏览: 2
在Java中,我们可以创建一个简单的算数运算符接口(Operator),然后为加法、减法、乘法、除法和取余操作分别实现这个接口。这里是一个基本的实现示例:
```java
// 定义一个算术运算接口
interface ArithmeticOperator {
double operate(double a, double b);
}
// 加法运算实现
class Addition implements ArithmeticOperator {
@Override
public double operate(double a, double b) {
return a + b;
}
}
// 减法运算实现
class Subtraction implements ArithmeticOperator {
@Override
public double operate(double a, double b) {
return a - b;
}
}
// 乘法运算实现
class Multiplication implements ArithmeticOperator {
@Override
public double operate(double a, double b) {
return a * b;
}
}
// 除法运算实现 (注意:除数不能为0)
class Division implements ArithmeticOperator {
@Override
public double operate(double a, double b) {
if (b != 0) {
return a / b;
} else {
throw new IllegalArgumentException("Division by zero is not allowed.");
}
}
}
// 取余运算实现 (模运算)
class Modulus implements ArithmeticOperator {
@Override
public double operate(double a, double b) {
return Math.floorMod(a, b);
}
}
public class CalculatorWindow {
private ArithmeticOperator operator;
public CalculatorWindow(ArithmeticOperator op) {
this.operator = op;
}
public double calculate(double num1, double num2) {
return operator.operate(num1, num2);
}
public static void main(String[] args) {
CalculatorWindow calculator = new CalculatorWindow(new Addition());
System.out.println("Addition: " + calculator.calculate(5, 3));
calculator.operator = new Subtraction();
System.out.println("Subtraction: " + calculator.calculate(5, 3));
// 更改其他运算...
}
}
```
在这个例子中,`CalculatorWindow`类接受一个`ArithmeticOperator`类型的实例,并通过它来进行计算。用户可以在运行时切换不同的运算类型。
阅读全文