简体   繁体   English

将 Double.parseDouble 用于已被转换为 String 的对象时出错

[英]Error while using Double.parseDouble to an Object that has been caste as String

I'm writing an infix evaluator program and I'm having trouble with this statement:我正在编写一个中缀求值程序,但我在使用此语句时遇到了问题:

c = Double.parseDouble((String) operands.pop());

"operands" is a stack which stores the operands. “操作数”是一个存储操作数的堆栈。 The .pop() method returns an object of type T (Since the stack is an ArrayList of type T). .pop() 方法返回一个 T 类型的对象(因为堆栈是一个 T 类型的 ArrayList)。 Since Double.parseDouble requires a string as parameter, I have caste it to a string.由于 Double.parseDouble 需要一个字符串作为参数,因此我将其转换为字符串。

However, I am receiving this error: java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String但是,我收到此错误: java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.String

What mistake have I made?我犯了什么错误?

The exception is actually happening on the expression异常实际上发生在表达式上

(String) operands.pop()

You can't cast a double to a string using (String) because it is not a safe cast.您不能使用(String)将 double 转换为字符串,因为它不是安全转换。

The compiler is telling you that the value given by operands.pop() is already a double!编译器告诉你, operands.pop()给出的值已经是双operands.pop()值了!

If you want to do the cast, you will need to use the toString() method on it first.如果要进行强制转换,则需要先对其使用toString()方法。

Exception is indicating that pop method is returning object of java.lang.Double() so no need to cast and parse it.异常表明 pop 方法正在返回 java.lang.Double() 的对象,因此无需强制转换和解析它。 Even if you want to cast and parse because of some reason then use String.valueOf(operands.pop()).即使您由于某种原因想要进行转换和解析,也可以使用 String.valueOf(operands.pop())。

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

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