9.28

发布时间 2023-10-26 22:26:10作者: 看海不为月
import java.util.Stack;

public class ArithmeticExpressionEvaluator {
    public static void main(String[] args) {
        String expression = "11 / (5 * 2)";  // 替换为你的题目字符串

        double result = evaluateArithmeticExpression(expression);
        System.out.println("表达式计算结果: " + result);
    }

    public static double evaluateArithmeticExpression(String expression) {
        // 移除空格
        expression = expression.replaceAll("\\s", "");

        // 定义操作数栈和运算符栈
        Stack<Double> operandStack = new Stack<>();
        Stack<Character> operatorStack = new Stack<>();

        // 定义运算符优先级
        int[] precedence = new int[256];
        precedence['+'] = 1;
        precedence['-'] = 1;
        precedence['*'] = 2;
        precedence['/'] = 2;

        for (int i = 0; i < expression.length(); i++) {
            char ch = expression.charAt(i);

            if (Character.isDigit(ch)) {
                // 处理操作数
                StringBuilder sb = new StringBuilder();
                while (i < expression.length() && Character.isDigit(expression.charAt(i))) {
                    sb.append(expression.charAt(i));
                    i++;
                }
                i--;
                double operand = Double.parseDouble(sb.toString());
                operandStack.push(operand);
            } else if (ch == '(') {
                // 左括号入栈
                operatorStack.push(ch);
            } else if (ch == ')') {
                // 右括号,弹出括号内的运算符进行计算
                while (!operatorStack.isEmpty() && operatorStack.peek() != '(') {
                    evaluateTopOperator(operandStack, operatorStack);
                }
                if (!operatorStack.isEmpty() && operatorStack.peek() == '(') {
                    operatorStack.pop();  // 弹出左括号
                } else {
                    throw new IllegalArgumentException("括号不匹配");
                }
            } else if (isOperator(ch)) {
                // 处理运算符
                while (!operatorStack.isEmpty() && operatorStack.peek() != '(' &&
                        precedence[ch] <= precedence[operatorStack.peek()]) {
                    evaluateTopOperator(operandStack, operatorStack);
                }
                operatorStack.push(ch);
            } else {
                throw new IllegalArgumentException("无效的字符: " + ch);
            }
        }

        // 处理剩余的运算符
        while (!operatorStack.isEmpty()) {
            evaluateTopOperator(operandStack, operatorStack);
        }

        // 返回最终结果
        if (operandStack.size() == 1 && operatorStack.isEmpty()) {
            return operandStack.pop();
        } else {
            throw new IllegalArgumentException("无效的表达式");
        }
    }

    private static boolean isOperator(char ch) {
        return ch == '+' || ch == '-' || ch == '*' || ch == '/';
    }

    private static void evaluateTopOperator(Stack<Double> operandStack, Stack<Character> operatorStack) {
        if (operandStack.size() < 2 || operatorStack.isEmpty()) {
            throw new IllegalArgumentException("无效的表达式");
        }
        double operand2 = operandStack.pop();
        double operand1 = operandStack.pop();
        char operator = operatorStack.pop();
        double result = performOperation(operand1, operator, operand2);
        operandStack.push(result);
    }

    private static double performOperation(double operand1, char operator, double operand2) {
        switch (operator) {
            case '+':
                return operand1 + operand2;
            case '-':
                return operand1 - operand2;
            case '*':
                return operand1 * operand2;
            case '/':
                if (operand2 != 0) {
                    return operand1 / operand2;
                } else {
                    throw new ArithmeticException("除零错误");
                }
            default:
                throw new IllegalArgumentException("无效的操作符");
        }
    }
}
复制代码
复制代码
这段代码的作用如下:
expression = expression.replaceAll("\\s", "");

这行代码使用正则表达式,将 expression 中的空格字符去除掉。它使用 replaceAll 方法,第一个参数是表示空格字符的正则表达式 "\\s",第二个参数为空字符串 "",表示将空格字符替换为空。
接下来是变量的定义和初始化:
Stack&lt;Double&gt; operandStack = new Stack&lt;&gt;();
Stack&lt;Character&gt; operatorStack = new Stack&lt;&gt;();

这两行代码分别定义并创建了一个操作数栈 operandStack 和一个运算符栈 operatorStack,它们是用来存储计算过程中的操作数和运算符的栈。
int[] precedence = new int[256];
precedence['+'] = 1;
precedence['-'] = 1;
precedence['*'] = 2;
precedence['/'] = 2;