简体   繁体   中英

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:

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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