Question

My code works perfectly as far as I can see but I still get the error "Cannot cast from Object to char" and I was wondering if anyone could explain to me what the problem is and if I can do it another way that does not cause an error.

This is the bit of code causing the error char op = (char) term;. It is from an infix to postfix converter

//Take terms off the queue in proper order and evaluate
private double evaluatePostfix(DSAQueue<Object> postfixQueue) {
    DSAStack<Double> operands = new DSAStack<Double>();
    Object term; 

    //While still terms on queue, take term off.
    while(!postfixQueue.isEmpty()) {
        term = postfixQueue.dequeue();
        if(term instanceof Double) { //If term is double put on stack
            operands.push((Double) term);
        }
        else if(term instanceof Character) { //If term is character, solve
            double op1 = operands.pop();
            double op2 = operands.pop();
            char op = (char) term;
            operands.push(executeOperation(op, op2, op1));
        }
    }
    return operands.pop(); //Return evaluated postfix
}

Any help (even pointing me to some reading) would be much appreciated.

Was it helpful?

Solution

You can change this line:

char op = (Character) term;

Explanation: in Java 6 you can't cast an Object to a primitive type, but you can cast it to Character (which is a class) and unboxing does the rest :)

Edit: Alternatively, you can bump the language level of your project up to Java 7 (or 8...)

OTHER TIPS

There is nothing wrong with your code. Since term is an instance of Character you could even assign it directly without casting as char op = term if you are using jdk 1.5+

One possibility i could see is the compiler compliance level used. You might have a JDK 1.5+ but you are compiling your project in a lower level. If you are using eclipse check for JDK compliance level in Project->properties->Java Compiler

If you are directly compiling or using Ant build check for -source & -target options.

And just for your info, as far as i know Object to primitive casting was introduced in JDK 1.7. So if you are using JDk 1.7+ you could wirte as

Object term = 'C';
char op = (char) term;

Java can't auto unbox and cast in one operation, which is what you're trying to do. Instead, cast it to Character and java will auto unbox it OK:

char op = (Character) term;

You can't cast from an object to a primitive data type (or vice versa). They are two very different things.

Java lang package has classes that correspond to each primitive: Float for float, Boolean for boolean..

As others already stated, you should cast the object to Character and not char.

you have to chang

char op = (Character) term;

because you have to cast with class refference not using the primitive type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top