Java检查后缀中的运算符优先级

时间:2018-04-08 17:33:45

标签: java

我正在为我们在一个方法中从中缀转换为后缀的类完成此代码,并在另一个方法中计算后缀。我首先遇到的问题是转换部分的逻辑不正确,因为即使我运行12-3,后缀显示为3而不是12 3 - 。其次,我不确定在方法中如何检查优先级。计算器框架代码已经给出了

在这个问题中解决了==和.equals()之间的差异 How do I compare strings in Java? 但我尝试将delims字符串解析为字符,后缀仍然给出了相同的结果3.

public String infixToPostfix() {

Stack<String> s = new Stack<>();

String expression = jtfInfix.getText(); // retrieves one long string
String delims = "+-*/() ";

StringTokenizer strToken = new StringTokenizer(expression, delims, true); // without true, it'll skip the tokens
                                                                            // and move onto the next string

String postFix = "";

while (strToken.hasMoreTokens()) {
    String token = strToken.nextToken();
    // if the next token is a number, append it to the result
    if (token != delims) {
        postFix += token;
    } else if (token == "(") {
        s.push(delims);
        while (delims != ")") {
            postFix += token;
            try {
                s.pop();
            } catch (StackEmptyException see) {
                see.printStackTrace();
            }
        }
    }
    // else if the next token is an operator
    else if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
        // compare the token to the top of the stack to determine precedence

        // while the operator on the stack has precedence

        // pop the top element off the stack and append it to the result
        try {
            postFix += s.pop();
        } catch (StackEmptyException see) {
            see.printStackTrace();
        }
        // push the current operator on the stack
        s.push(token);
    }
    while (!s.isEmpty()) {
        try {
            postFix += s.pop();
        } catch (StackEmptyException see) {
            see.printStackTrace();
        }
    }

}
return postFix;

}

0 个答案:

没有答案