用java写一个能计算俩个数的加减乘除的程序
时间: 2024-10-22 12:06:13 浏览: 10
在Java中,你可以创建一个名为`Calculator`的类,然后定义一个抽象方法`performOperation`,让各个具体的运算类来实现这个方法。这是一个简单的例子:
```java
abstract class Calculator {
public abstract double calculate(double num1, double num2, String operation);
}
class AddCalculator extends Calculator {
@Override
public double calculate(double num1, double num2, String operation) {
if ("add".equals(operation)) {
return num1 + num2;
}
throw new IllegalArgumentException("Unsupported operation for addition.");
}
}
class SubtractCalculator extends Calculator {
@Override
public double calculate(double num1, double num2, String operation) {
if ("subtract".equals(operation)) {
return num1 - num2;
}
throw new IllegalArgumentException("Unsupported operation for subtraction.");
}
}
class MultiplyCalculator extends Calculator {
@Override
public double calculate(double num1, double num2, String operation) {
if ("multiply".equals(operation)) {
return num1 * num2;
}
throw new IllegalArgumentException("Unsupported operation for multiplication.");
}
}
class DivideCalculator extends Calculator {
@Override
public double calculate(double num1, double num2, String operation) {
if ("divide".equals(operation) && num2 != 0) {
return num1 / num2;
} else {
throw new IllegalArgumentException("Cannot divide by zero.");
}
}
}
public class Main {
public static void main(String[] args) {
Calculator add = new AddCalculator();
Calculator subtract = new SubtractCalculator();
Calculator multiply = new MultiplyCalculator();
Calculator divide = new DivideCalculator();
double resultAdd = add.calculate(5, 3, "add");
double resultSubtract = subtract.calculate(5, 3, "subtract");
double resultMultiply = multiply.calculate(5, 3, "multiply");
double resultDivide = divide.calculate(5, 3, "divide");
System.out.println("Add: " + resultAdd);
System.out.println("Subtract: " + resultSubtract);
System.out.println("Multiply: " + resultMultiply);
System.out.println("Divide: " + resultDivide);
}
}
```
在这个例子中,用户可以在`main`函数中选择不同的计算器对象来进行相应的操作。
阅读全文