10.7

软件构造作业
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);
 
    }
 
}
posted @ 2025-01-07 22:33  kxzzow  阅读(7)  评论(0)    收藏  举报