简体   繁体   English

Java Stack类强制转换异常

[英]Java Stack Class Cast Exception

I have to write a program that reads a postfix expression from the keyboard and store it in a stack. 我必须编写一个程序,从键盘读取后缀表达式并将其存储在堆栈中。 I keep getting a class cast exception at case "+" : and I can not figure it out. 在“+”的情况下我一直得到一个类强制转换异常:我无法理解它。 Is anyone able to help me? 有人能帮助我吗?

    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;  

You're popping stuff off your stack without checking what they are. 你正在从堆栈中弹出东西而不检查它们是什么。 This is almost certainly going to cause you trouble. 这几乎肯定会给你带来麻烦。 How did you build your stack in the first place? 你是如何在第一时间建立堆栈的? Do you KNOW you've been doing something like: 你知道你做过类似的事情吗?

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

It looks like you're trying to read a series of string inputs from your stack and convert the numeric ones using casting when you need to use conversion. 看起来您正在尝试从堆栈中读取一系列字符串输入,并在需要使用转换时使用转换转换数字输入。

Assuming your users have caused some stack pushes like this 假设你的用户已经造成了这样的堆栈推送

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

The pop routine would look like this: pop例程如下所示:

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

Casting is for when the object IS of the type you want. 转换是指对象IS所需的类型。 Conversion is for when you want it to become the right type. 转换适用于您希望它成为正确类型的时间。

I would also make your stack generic of type String to avoid doubt: 我也会让你的堆栈类型为String的通用,以避免产生疑问:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM