java - 无法从 Object 转换为 char

标签 java casting

据我所知,我的代码运行完美,但我仍然收到错误“无法从对象转换为字符”,我想知道是否有人可以向我解释问题所在,以及我是否可以用另一种方式来解决不会导致错误。

这是导致错误 char op = (char) term; 的代码位。它是从中缀到后缀的转换器

//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
}

任何帮助(甚至指点我一些阅读)将不胜感激。

最佳答案

你可以改变这一行:

char op = (Character) term;

说明:在 Java 6 中,您不能将 Object 转换为原始类型,但您可以将其转换为 Character(这是一个类),剩下的就是拆箱 :)

编辑: 或者,您可以将项目的语言级别提高到 Java 7(或 8...)

关于java - 无法从 Object 转换为 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23382888/

相关文章:

java - BufferedInputStream.read(byte[] b, int off, int len) 中的 off 参数

java - Swing 设计器 & 布局 & 文本字段限制

java - 将 jar 文件保存在 WAR 和 Tomcat lib 文件夹中的区别

c - 如何将字符数组转换为 uint8_t

c++ - 类型转换:有什么区别。内置类型的 T(value) 和 (T)value?

c++ - 定义将对内存进行操作的函数时,将地址传递为 void* 还是 uint8* 更正确?

java - 使用 grayVal 到 Ascii 字符的转换将图像转换为 Ascii 码

C:为什么将 int 转换为 float 输出 0.000?

c++ - 防止派生类强制转换为基类

java - 依赖 Maven 项目的测试失败