使用堆栈的Java中的后缀表达式的前缀

问题描述 投票:0回答:1

我正在制作一种将前缀符号转换为后缀符号的方法。我在开关和机箱上遇到麻烦。它应该从扫描仪读取并识别字符串,但是当遇到操作数时,我将其转换为char并将其添加到我的堆栈中。返回结果之前,我必须将char添加回字符串。有提示吗?

private static String prefixToPostfix(String prefix) {
        ArrayStack<Character> operators = new ArrayStack<>();
        String postfixResult = "";
        Scanner scan = new Scanner(prefix);
        while(scan.hasNext()) {
            String token = scan.next();
            switch(token) {
            case "+": case "-": case "/": case "*":
                // All operators are treated the same
                // TODO: Put on stack
                char s = token.charAt(0);
                operators.push(s);
                break;
            case ")":
                // TODO: pop stack to put in result, before adding )
                token += String.valueOf(operators.pop());

                break;
            default:
                postfixResult += " "+token+" ";
            }
        }
        if(!operators.isEmpty()) throw new IllegalStateException();
        scan.close();
        return postfixResult;
    }
java stack lisp postfix-notation
1个回答
0
投票

在“)”情况下,您有休息时间,因此将不执行默认值。只需删除中断,您就可以了

© www.soinside.com 2019 - 2024. All rights reserved.