软件构造作业
1、操作类:Operation
public class Operation {
private double operand1;
private double operand2;
private char operator;
public Operation(double operand1, double operand2, char operator) {
this.operand1 = operand1;
this.operand2 = operand2;
this.operator = operator;
}
public double calculate() {
switch (operator) {
case '+':
return operand1 + operand2;
case '-':
return operand1 - operand2;
default:
throw new IllegalArgumentException("Unsupported operator: " + operator);
}
}
}
2、表达式类:Expression
import java.util.ArrayList;
import java.util.List;
public class Expression {
private List<Operation> operations;
public Expression() {
this.operations = new ArrayList<>();
}
public void addOperation(Operation operation) {
operations.add(operation);
}
public double evaluate() {
double result = 0;
for (Operation operation : operations) {
result += operation.calculate();
}
return result;
}
}
3、输入类:InputHandler
public class InputHandler {
public Expression parseExpression(String input) {
Expression expression = new Expression();
String[] tokens = input.split(" ");
for (int i = 0; i < tokens.length; i += 2) {
double operand1 = Double.parseDouble(tokens[i]);
char operator = tokens[i + 1].charAt(0);
double operand2 = Double.parseDouble(tokens[i + 2]);
Operation operation = new Operation(operand1, operand2, operator);
expression.addOperation(operation);
}
return expression;
}
}
4、输出类:OutputHandler
public class OutputHandler {
public void printResult(double result) {
System.out.println("The result is: " + result);
}
}
5、主程序类:CalculatorApp
import java.util.Scanner;
public class CalculatorApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
InputHandler inputHandler = new InputHandler();
OutputHandler outputHandler = new OutputHandler();
System.out.println("Enter an expression (e.g., '2 + 3 - 4'): ");
String input = scanner.nextLine();
Expression expression = inputHandler.parseExpression(input);
double result = expression.evaluate();
outputHandler.printResult(result);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?