English 中文(简体)
为什么在Java中从堆栈转换为int不运行?
原标题:
  • 时间:2009-02-21 17:08:32
  •  标签:

我在尝试将存储在栈中的字符转换为整数,我做的是这样的。

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();
问题回答

你没有展示 a 的声明,但我怀疑它是一个 char 类型。那么它就会被自动装箱为 Character,当你向 Integer 进行强制转换时,转换就会失败。

如果您更改代码使用:

operands.push((int) a);

这应该将char转换为int,然后装箱到Integer,然后你就可以了。

或者,使用:

// Implicit conversion from char to int
int op1 = ((Character) operands.peek()).charValue();

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

operands.push((int) (a- 0 ));

或者

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 f或者 clarity.

你一定在使用1.5版本。这里提供一种正确操作方式:

if (a >=  0  && a <=  9 ) {
    operands.push(a);
}

char c = operands.peek();
int op1 = (int) c; //check Character.isDigit(c), if there is other stuff in the stack

将字符转换为整数的简单方法是:

if (a >=  0  && a <=  9 ) {
    operands.push(a -  0 ); // converts a char to an int.
}
int op1 = (Integer) operands.peek();

你确定你实际上将任何东西推入堆栈了吗?如果没有,那么你的强制转换行将抛出EmptyStackException。你正在遇到哪个异常?

没有看到StackLinked的定义真的很难,那是你自己的类之一吗?

I can think of several options: The stack is somehow empty (e.g., a was not one of these characters ).

或者a被保存为堆栈中的字符(而不是char),然后转换为整数失败。您可能需要先从Character中获取char。

你的例子可能有点不明确,这是我的假设:

  • 你正在使用Java 1.5的语言特性(由于装箱/拆箱)。

  • 操作数类似于Stack<Character>的行为。

当你将一个字符压入栈中时,它会被封装成一个 Character。你不能将 Character 实例强制转换成 Integer。你必须获取原始数值,然后将其强制转换为整数原始类型。

请尝试这个:

int op1 = (int) operands.peek().charValue();

将字符转换为整数。

最简单的途径就是这个:

operands.push(Integer.parseInt(Character.toString(a)));

你正在推一个字符,而不是整数。你需要说类似于这样的话:

Char op1 = (Char)operands.peek();
int opcode = Char.digit(op1.charValue(),10);

我的Java有些生疏,如果一些方法名稍有不同请见谅。

此外,如果你的Peek方法返回空值(因为你的if语句被判定为 false),那么你的代码将会崩溃。





相关问题