使用堆栈在java中获取infix / postfix的错误输出

时间:2016-03-22 01:29:39

标签: java stack stringtokenizer postfix-notation infix-notation

对于输入(1 + 3)*(1 + 3)我输出为1 3 + * 1 3 +,当它应为1 3 + 1 3 + *时。我已经调试过,无法弄清楚为什么乘法直到最后都没有。我不是在checkOp()中正确比较它吗?

public String infixToPostfix() throws StackEmptyException{

    Stack<String> s = new Stack<String>();
    String expression = jtfInfix.getText();
    String delims = "+-*/()123456789 ";
    StringTokenizer strToken = new StringTokenizer(expression, delims, true);
    String result = "";

    while(strToken.hasMoreTokens()){

        String token = strToken.nextToken();

        if(token.equals("(")){
            s.push(token);
        }   
        else if(token.equals(")")){

            while(s.peek().equals("(") != true){
                result += " " + s.pop();
            }
        }//first elseif
        else if (checkOp(token)){
            if(s.isEmpty() == true) {
                s.push(token);
            }
            else {
                if(getOrder(token) < findOrder(s.peek())) {
                    result += " " + s.pop();
                    s.push(token);
                }
                else {
                    s.push(token);
                }
            }
        }
        else {
            result += " " + token;
        }
    }
    while(s.isEmpty()) {
        result += s.pop();
    }

    return result;
}// infixToPostFix()

public int findOrder(String token) {
    int order = 0;
    if((token.equals("+")) || (token.equals("-"))) {
        order = 1;
    }
    else if((token.equals("*")) || (token.equals("%"))) {
        order = 2;
    }
    else if(token.equals(")")) {
        order = 0;
    }
    return order;
}

public int getOrder(String token) {
    int order = 0;
    if((token.equals("+")) || (token.equals("-")) ) {
        order = 1;
    }
    else if((token.equals("*"))  || (token.equals("%")) ) {
        order = 2;
    }
    return order;
}


private boolean checkOp(String token) {
    return ((token.equals("+"))  ||  (token.equals("-"))  || (token.equals("*"))  || 
            (token.equals("%"))  );            

}

1 个答案:

答案 0 :(得分:1)

有几个错误

首先,您需要在匹配后弹出括号

java

并且您希望在完成后将所有内容从堆栈中弹出

while(s.peek().equals("(") != true){
    result += " " + s.pop();
}
s.pop(); // pop the matching left parenthesis

应该是

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

作为评论记录有助于了解发生的情况。