java—将中缀转换为后缀并获取emptystackexception

vbopmzt1  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(279)

我正在做一个项目,将中缀符号转换为后缀符号,然后计算公式。我为每个操作符建立了优先级。当我使用converttopostfix方法时,我得到了一个异常。我理解反向波兰语符号计算器的概念,我正在努力用我的代码来实现它。我是新的堆栈溢出,所以如果有什么东西,可能看起来有点混乱,让我知道,我会尝试编辑它。

import java.util.Stack;
public class RPNCalctest {

public static void main( String[] args) throws  InvalidInfixEquationException {
    String example= "3+4/3*2"; //postfix notation would be 3 4 3 / 2 * +

    System.out.println(ConvertToPostfix(example));
    // TODO
}
//establish precedence
static int precedence(String c){
    switch(c){
        case"+":
        case"-":
            return 1;
        case"*":
        case"/":
            return 2;

        case")":
            return 3;
        case"(":
            return 4;
        default:
            return -1;
    }
}

// Precondition: every operator/operand will be separated by at least one space
public static String ConvertToPostfix(String infix) throws InvalidInfixEquationException {

    String[] tokens = infix.split(" ");
    String result = "";
    Stack<String> stack = new Stack<>();
    for (int i = 0; i < tokens.length; i++) {
        String current = tokens[i];

        if (precedence(current) > 0) {

            while (!stack.isEmpty() && precedence(stack.peek()) >= precedence(current)) {
                result += stack.pop() + " ";
            }
            stack.push(current);
        } else {
            result += current + " ";
        }
    }

    for (int i = 0; i <= stack.size(); i++) {
        result += stack.pop();
    }
    return result;
}

}

Exception in thread "main" java.util.EmptyStackException
at java.base/java.util.Stack.peek(Stack.java:101)
at java.base/java.util.Stack.pop(Stack.java:83)
at RPNCalctest.ConvertToPostfix(RPNCalctest.java:50)
at RPNCalctest.main(RPNCalctest.java:7)
pwuypxnk

pwuypxnk1#

你的问题在这里。你多出一个入口。

for (int i = 0; i <= stack.size(); i++) {
    result += stack.pop();
}

考虑大小=2。执行i=0,1,2的循环。
我假设'pop'行是堆栈跟踪中指示的第53行,因此作为将来的参考,这是有用的调试信息,您应该使用它。
如果对循环进行编码,可能会更清楚:

while (!stack.isEmpty()) {
      result += stack.pop();
 }

不需要外部变量“i”。

相关问题