选用Java语言实现一个计算程序,保持代码的健壮性,将计算和显示分开。
时间: 2024-10-25 19:11:16 浏览: 8
在Java中,为了实现一个健壮的计算程序并保持代码模块化,我们可以采用面向对象的设计原则。首先,创建一个`Calculator`接口,包含基本的计算方法如`add`, `subtract`, `multiply`, 和 `divide`:
```java
public interface Calculator {
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b) throws ArithmeticException;
}
```
然后,为每个具体的计算操作(如加法、减法等)实现这个接口,比如`AdditionCalculator` 和 `SubtractionCalculator`:
```java
public class AdditionCalculator implements Calculator {
@Override
public double add(double a, double b) {
return a + b;
}
// ...其他计算方法实现
}
public class SubtractionCalculator implements Calculator {
@Override
public double subtract(double a, double b) {
return a - b;
}
}
```
接着,我们创建一个`Display`类,用于接收`Calculator`对象并显示结果,实现与显示逻辑的分离:
```java
public class Display {
private Calculator calculator;
public Display(Calculator calculator) {
this.calculator = calculator;
}
public void displayResult(String operation, double result) {
System.out.println("运算结果 (" + operation + "): " + result);
}
public void performCalculation(String operation, double a, double b) {
try {
double result = calculator.calculate(operation, a, b);
displayResult(operation, result);
} catch (ArithmeticException e) {
System.out.println("错误:除数不能为零");
}
}
}
```
现在你可以这样使用它:
```java
public static void main(String[] args) {
Display display = new Display(new AdditionCalculator());
display.performCalculation("加法", 5, 3); // 输出:运算结果 (加法): 8
display = new Display(new SubtractionCalculator());
display.performCalculation("减法", 10, 2); // 输出:运算结果 (减法): 8
}
```
阅读全文