简体   繁体   中英

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). Since Double.parseDouble requires a string as parameter, I have caste it to a string.

However, I am receiving this error: 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.

The compiler is telling you that the value given by operands.pop() is already a double!

If you want to do the cast, you will need to use the toString() method on it first.

Exception is indicating that pop method is returning object of java.lang.Double() so no need to cast and parse it. Even if you want to cast and parse because of some reason then use String.valueOf(operands.pop()).

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