软件构造作业

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 @   不会JAVA的小袁  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示