Postfix表示法中的EmptyStackException

时间:2018-10-08 03:10:20

标签: java exception postfix-notation

当我尝试运行后缀表达式时,由于我的字符串有两个背对背的操作数,因此我得到了EmptyStackException。我不知道如何在我的堆栈中捕获它。任何想法都可以得到赞赏。

import java.util.Stack;
import java.util.Queue;

public class postFixCalc extends Program2Test{
    static Program2Test<Integer> calcStack = new Program2Test<>();

    private static int calc1(String exp) {
        Stack<Integer> calc1Stack = new Stack<>();

        for(int i = 0; i<exp.length(); i++) {
            char c = exp.charAt(i);
            if(Character.isDigit(c))
                calc1Stack.push(c-'0');
            else {
                int val1= calc1Stack.pop();
                int val2= calc1Stack.pop();

                switch(c){
                    case '+':
                        calc1Stack.push(val2+val1);
                        break;

                    case '-':
                        calc1Stack.push(val2-val1);
                        break;

                    case '/':
                        calc1Stack.push(val2/val1);
                        break;

                    case '*':
                        calc1Stack.push(val2*val1);
                        break;
                }
            }
        }
        return calc1Stack.pop();
    }
    public static void main(String[] args) {

        // TODO Auto-generated method stub
        String exp = "12+4*5-";     
        System.out.println("Your Answer is: " + calc1(exp));
        String exp2 = "(12*4*1-)/53+";
        System.out.println("Your answer is: " + calc1(exp2));



    }

}

1 个答案:

答案 0 :(得分:0)

将此代码添加到您的代码中,以确保您没有从空堆栈中弹出:

if(!calc1Stack.empty()) {
    int val1= calc1Stack.pop();
}

if(!calc1Stack.empty()) {
    int val2= calc1Stack.pop(); 
} 

然后处理else条件。