Rpn转换中的空堆栈异常

时间:2017-03-08 10:51:48

标签: android stack

我在android中为rpn计算编写代码,当我在括号内有运算符时崩溃了。例如(89 + 7)崩溃,但(8)+7输出15。 这是我用于中缀到后缀转换的方法:

       private static List<String> convert(String input) {
            int p = 0;
            String pfb = "";
            Stack<Character> chara = new Stack<>();
            List<String> pfa = new ArrayList<>();
            for (int i = 0; i < input.length(); i++) {
                char ch = input.charAt(i);
                if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
                    if (pfb.length() > 0) {
                        pfa.add(pfb);
                    }
                    pfb = "";
                    if (chara.empty()) {
                        chara.push(ch);
                    } else {
                        Character chTop = (Character) chara.peek();
                        if (chTop == '*' || chTop == '/')
                            p = 1;
                        else if (chTop == '+' || chTop == '-')
                            p = 0;
                        if (p == 1) {
                            if (ch == '+' || ch == '-') {
                                pfa.add(String.valueOf(chara.pop()));
                                i--;
                                Log.d("pfa", "" + input.length() + "" + i);
                            } else { // Same
                                pfa.add(String.valueOf(chara.pop()));
                                i--;
                            }
                        } else {
                            if (ch == '+' || ch == '-' && chara.peek() != '(') {

                                pfa.add(String.valueOf(chara.pop()));
                                chara.push(ch);
                            } else
                                chara.push(ch);
                        }
                    }
                } else if (ch == '(') {
                    chara.push(ch); 
    //                Log.d("St",""+chara.peek());


                } else if (ch == ')') {

   `//Code crashes here`           while (chara.peek() != '(' && !chara.empty()) {
                        pfa.add(String.valueOf(chara.pop()));
                    }
                    if (!chara.empty() && chara.peek() != '(')
                        return null; // invalid expression
                    else
                        chara.pop();


                } else {
                    pfb += ch;
                }
                //  Log.d("pfa",""+pfa+"");

            }
            return pfa;
        }

1 个答案:

答案 0 :(得分:0)

您编码崩溃是因为首先查看堆栈元素然后检查空状态。 应该是这样的 while(!chara.empty()&amp;&amp; chara.peek()!='(')