Java Stack类强制转换异常

时间:2015-03-05 00:09:34

标签: java generics stack classcastexception

我必须编写一个程序,从键盘读取后缀表达式并将其存储在堆栈中。在“+”的情况下我一直得到一个类强制转换异常:我无法理解它。有人能帮助我吗?

    String option = (String)stack.pop();
    while( stack  != null )
    {
        switch( option )
        {
        case "+":

            int left = (Integer)stack.pop();
            int right = (Integer)stack.pop();
            int result = left + right;
            String temp = (String) stack.pop();
            stack.push(result);

            break;  

2 个答案:

答案 0 :(得分:0)

你正在从堆栈中弹出东西而不检查它们是什么。这几乎肯定会给你带来麻烦。你是如何在第一时间建立堆栈的?你知道你做过类似的事情吗?

stack.push("string that becomes temp");
stack.push(new Integer(5));
stack.push(new Integer(3));
stack.push("+")

答案 1 :(得分:0)

看起来你正在尝试从堆栈中读取一系列字符串输入,并在需要使用转换时使用转换来转换数字输入。

假设您的用户已经引起了一些像这样的堆栈推送

stack.push("1234");
stack.push("1");
stack.push("+");

pop例程如下所示:

int left = Integer.parseint(stack.pop());
int right = Integer.parseint(stack.pop());
int result = left + right;

转换适用于所需类型的对象IS。转换适用于您希望它成为正确类型的时间。

我还会让你的堆栈类型为String的泛型,以避免产生疑问:

Stack<String> stack = new ....;