当前方法“evaluatePostfix”正在运行但打印出错误的结果java

问题描述

我已经编写了我的代码,它是一个使用堆栈的链表。该程序采用中缀形式并将其转换为后缀,目前正在输出(使用我的输入和输出文件)正确的转换。但是,我不明白如何让evaluatePostFix 方法正常工作。我的问题是打印出错误的结果,我不知道为什么。任何帮助表示赞赏!

我目前的evaluatePostfix方法

 public static int evaluatePostfix(String postfix) {
        
     
        Stack<Integer> stack = new Stack<>(); 

        Stack<Character> operatorStack = new Stack<>();
        
        int count = 0;
        int operandTwo = '0';
        int operandOne = '0';
        
      while (count < postfix.length() && count >= 0) {
          
          char nextCharacter = postfix.charat(count);
          
            switch(nextCharacter) {
                    case '^':
                        operatorStack.push (nextCharacter);
                        break;
                    case '+':
                        stack.push(operandTwo + operandOne);
                    case '-':
                        stack.push(operandTwo - operandOne);
                    case '*':
                        stack.push(operandTwo * operandOne);
                    case '/':
                        stack.push(operandTwo / operandOne);
                       
                int result1 = nextCharacter;
                stack.push(result1); 
                break;
                
           default: break;
          
            } //End switch
            
            count = count + 1;
        } //End while
 
        //return stack.pop();
        return stack.peek();
    } //End evaluatePostfix

解决方法

case '+':
     stack.push(operandTwo + operandOne);

case '-':
     stack.push(operandTwo - operandOne);
  • 您需要在其中包含一个 break 语句以避免陷入下一个 case 块。

  • 您需要先将这两个操作数 pop 移出您的堆栈,否则您将无法访问它们的值(它们也会保留在堆栈中)。

  • 一般来说,要调试此类代码,有用的工具是通过调试器逐步完成、插入 println 语句、编写单元测试以及在一张纸上推理流程和变量状态。