为什么从堆栈转换为int不能在Java中运行?

0 java casting

我正在尝试将存储在堆栈中的char转换为整数,这就是我所做的.

operands = new StackLinked();

if ( (a == '0') || (a == '1') || (a == '2') || (a == '3') || (a == '4') || 
     (a == '5') || (a == '6') || (a == '7') || (a == '8') || (a == '9') )
{
   operands.push(a);   /*Stor operands in the stack operands.*/
}

//This line crushes my program. I don't know why.
int op1 = ((Integer)operands.peek()).intValue();
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

您没有显示声明,a但我怀疑它是类型的char.那就是自动生成Character,所以当你施放到Integer演员阵容失败时.

如果您更改要使用的代码:

operands.push((int) a);
Run Code Online (Sandbox Code Playgroud)

应该转换charint然后盒子Integer,你将离开.

或者,使用:

// Implicit conversion from char to int
int op1 = ((Character) operands.peek()).charValue();
Run Code Online (Sandbox Code Playgroud)

编辑:请注意,上述解决方案最终会在a ='1'时给出op1 = 49,当a ='2'时op2 = 50等等.如果a ='1'时你真的想要op1 = 1你可以使用Character.digit或者(因为我们已经知道'a'在'0'到'9'的范围内)你可以减去'0',即

operands.push((int) (a-'0'));
Run Code Online (Sandbox Code Playgroud)

要么

int op1 = ((Character) operands.peek()).charValue() - '0';
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,演员实际上是多余的,因为减法的结果将是 - int而不是char- 但为了清楚起见,我会留在那里.