0

我有一个程序,该程序旨在接收包含前缀操作元素的 Queue<String>(即声明为“+ 4 2”而不是中缀“4 + 2”的操作),然后输出整数答案(假设永远不需要双精度,好吗?)。它适用于任何乘法或除法运算,但在任何加法或减法运算中都失败,更糟糕的是,以不一致的方式。例如,“- 5 1”的输出是 5,这表明它增加了一个额外的整数,但是“- 5 2”的输出是 2,这是一个太低的整数。我只是不明白这个错误的逻辑在哪里?

 public static int eval(Queue<String> s){
        String a=s.toString();
        String b= a.replaceAll("\\[","").replaceAll("\\]","").replace(", "," ");
        StringBuilder c=new StringBuilder();
        c.append(b);
        c.reverse();
        Stack<Integer> stack=new Stack<>();
        for (int i=0; i<c.length();i++){
            char current=c.charAt(i);
            if (current==' ')
                continue;
            if (current=='*'||current=='/'||current=='+'||current=='-'){
                Integer one = stack.pop();
                Integer two = stack.pop();
                Integer maybe;
                switch (current){
                    case '+':
                        maybe=one+two;
                    case '-':
                        maybe=one-two;
                    case '*':
                        maybe=one*two;
                    case '/':
                        maybe=one/two;
                        break;
                    default:
                       maybe=one;
                }
            stack.push(maybe);
            } else {
                StringBuilder maybe=new StringBuilder();
                while(Character.isDigit(current)){
                    maybe.append(current);
                    i++;
                    current=c.charAt(i);
                }
                i--;
                Integer n=Integer.parseInt(maybe.reverse().toString());
                stack.push(n);
            }
        }
        return stack.pop();
        }
    }

编辑:注意:它也只能输出简单的两个整数,一个运算符,方程,但我可以理解如何改变它。

4

0 回答 0