azure011328

导航

 

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);
    }
}

posted on 2024-09-28 14:42  淮竹i  阅读(5)  评论(0)    收藏  举报