You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Java Stack类无需自定义方法实现中缀表达式转后缀表达式

中缀转后缀表达式代码修复方案

现有代码的核心问题

  • switch分支缺少break语句:+/-的case执行完没有break,会直接落入*//的分支,导致运算符优先级赋值完全错误
  • 优先级判断逻辑错误:错误定义了两个变量存储优先级,且判断条件没有对比当前运算符和栈顶运算符的优先级,逻辑完全不符合中缀转后缀的规则
  • 栈清空时机错误:将遍历结束后才需要执行的栈清空逻辑写在了for循环内部,每遍历一个字符就会把栈内所有元素弹出,完全打乱转换逻辑
  • 空栈风险:处理右括号弹左括号时没有判断栈是否为空,括号不匹配时会直接抛出EmptyStackException导致程序崩溃
  • 优先级变量未重置:每次处理完运算符后没有重置优先级变量,残留值会干扰后续运算判断

修复后符合要求的代码

import javax.swing.*;
import java.util.Stack;

public class InfixToPostfix {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        String eq = JOptionPane.showInputDialog("Enter Equation");
        // 输入为空直接拦截
        if (eq == null || eq.trim().isEmpty()) {
            JOptionPane.showMessageDialog(f, "输入不能为空");
            return;
        }
        StringBuilder postfix = new StringBuilder();
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < eq.length(); i++) {
            char c = eq.charAt(i);
            // 自动跳过输入的空格
            if (c == ' ') continue;

            if (Character.isLetterOrDigit(c)) {
                postfix.append(c);
            } else if (c == '(') {
                stack.push(c);
            } else if (c == ')') {
                while (!stack.isEmpty() && stack.peek() != '(') {
                    postfix.append(stack.pop());
                }
                // 弹出左括号前判空,避免括号不匹配崩溃
                if (!stack.isEmpty()) {
                    stack.pop();
                }
            } else {
                // 计算当前运算符优先级
                int currentPriority = (c == '+' || c == '-') ? 1 : 2;
                // 栈顶运算符优先级大于等于当前优先级就弹出
                while (!stack.isEmpty() && stack.peek() != '(' 
                        && ((stack.peek() == '+' || stack.peek() == '-') ? 1 : 2) >= currentPriority) {
                    postfix.append(stack.pop());
                }
                stack.push(c);
            }
        }
        // 遍历完所有字符后清空栈内剩余运算符
        while (!stack.isEmpty()) {
            postfix.append(stack.pop());
        }

        JOptionPane.showMessageDialog(f, postfix.toString());
    }
}

内容的提问来源于stack exchange,提问作者John Silver

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:09:01