You haven't shown the declaration for a
but I suspect it's of type char
. That's then autoboxed to Character
, and so when you cast to Integer
the cast fails.
If you change your code to use:
operands.push((int) a);
that should convert from char
to int
then box to Integer
and you'll be away.
Alternatively, use:
// Implicit conversion from char to int
int op1 = ((Character) operands.peek()).charValue();
EDIT: Note that the above solutions would both end up giving op1=49 when a='1', op2=50 when a='2' etc. If you actually want op1=1 when a='1' you could either use Character.digit
or (as we already know that 'a' is in the range '0' to '9') you could just subtract '0', i.e.
operands.push((int) (a-'0'));
or
int op1 = ((Character) operands.peek()).charValue() - '0';
In the first case the cast is actually then redundant, as the result of the subtraction will be int
rather than char
- but I'd leave it there for clarity.