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

Java后缀表达式转换及运算符优先级检查问题求助

Fixing Your Infix-to-Postfix & Postfix Calculation Issues

Hey there! Let's work through your two calculator problems step by step—these are common hurdles when building expression evaluators, so you're in good company.

1. Fixing the Infix-to-Postfix Conversion Error (Input 12-3 outputs 3 instead of 12 3 -)

The root issue here is almost certainly that your code isn't handling multi-digit numbers correctly. Right now, it's probably reading each digit individually (treating 12 as 1 and 2 separate values) instead of grouping consecutive digits into a single number. Here's how to fix that:

  • When traversing your input string, add a check to read all consecutive digits whenever you hit a numeric character:
    // Example snippet for traversing the input string
    List<String> postfix = new ArrayList<>();
    Stack<String> opStack = new Stack<>();
    int i = 0;
    while (i < input.length()) {
        char c = input.charAt(i);
        if (Character.isDigit(c)) {
            // Build the full multi-digit number
            StringBuilder num = new StringBuilder();
            while (i < input.length() && Character.isDigit(input.charAt(i))) {
                num.append(input.charAt(i));
                i++;
            }
            postfix.add(num.toString());
        } else {
            // Handle operators/parentheses here
            // ... (your existing operator logic)
            i++;
        }
    }
    
  • This way, 12 gets added to the postfix list as a single element instead of two separate digits, which will fix the incorrect output for 12-3.

2. Implementing Operator Priority Checks

To handle operator precedence, create a helper method that assigns a priority value to each operator. Then, when processing operators during conversion, compare the current operator's priority with the stack's top operator's priority to decide whether to pop from the stack to the postfix list.

Step 1: Create a Priority Helper Method

private int getOperatorPriority(String op) {
    switch(op) {
        case "+":
        case "-":
            return 1;
        case "*":
        case "/":
            return 2;
        case "(":
            return 0; // Lower priority to keep it in the stack until ")" is found
        default:
            throw new IllegalArgumentException("Invalid operator: " + op);
    }
}

Step 2: Use the Priority Method in Conversion Logic

When you encounter an operator (not parentheses), do this:

// When processing an operator like "-"
while (!opStack.isEmpty() && getOperatorPriority(opStack.peek()) >= getOperatorPriority(currentOp)) {
    postfix.add(opStack.pop());
}
opStack.push(currentOp);
  • For parentheses: Push "(" directly to the stack. When you hit ")", pop all operators from the stack to postfix until you reach "(", then discard the "(".

Quick Reminder About == vs .equals()

Since you mentioned knowing the difference but still having issues: Always use .equals() when comparing operator strings (e.g., currentOp.equals("-") instead of currentOp == "-"). The == checks reference equality, which can fail if your operator strings are created differently, while .equals() checks actual string content.

Final Notes

Once you fix the multi-digit handling and add the priority logic, test with 12-3 again—you should get the correct postfix expression 12 3 -. Then you can use that postfix list in your calculation method, which can process each element: push numbers to a stack, and when hitting an operator, pop two numbers, apply the operation, and push the result back.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:00:34