java.math.biginger可以';不要转换为java.lang.Long
我正在编写一个代码来计算后缀表达式。数字非常大,所以我决定使用BigInteger。我应该将两个数字存储到链表中,计算它们的总和,将结果存储在第三个列表中,然后显示答案。但是,我得到了以下异常:java.lang.ClassCastException:java.math.BigInteger不能转换为java.lang.Longjava.math.biginger可以';不要转换为java.lang.Long,java,biginteger,Java,Biginteger,我正在编写一个代码来计算后缀表达式。数字非常大,所以我决定使用BigInteger。我应该将两个数字存储到链表中,计算它们的总和,将结果存储在第三个列表中,然后显示答案。但是,我得到了以下异常:java.lang.ClassCastException:java.math.BigInteger不能转换为java.lang.Long public static void pfEval(String exp) { Stack s2 = new Stack(); int i=0;
public static void pfEval(String exp)
{
Stack s2 = new Stack();
int i=0;
BigInteger ans = BigInteger.valueOf(0);
BigInteger op1 = BigInteger.valueOf(0);
BigInteger op2 = BigInteger.valueOf(0);
while(i<exp.length()-1)
{
BigInteger op = BigInteger.valueOf(0);
if(exp.charAt(i) == ' ')
i++;
if((exp.charAt(i) >= '0')&&(exp.charAt(i) <= '9'))
{
while(exp.charAt(i) != ' ')
{
op = op.multiply(BigInteger.valueOf(10));
op = op.add(BigInteger.valueOf(exp.charAt(i)-48));
i++;
}
s2.push(op);
}
else
{
op1 = BigInteger.valueOf((long)s2.pop());
op2 = BigInteger.valueOf((long)s2.pop());
switch(exp.charAt(i))
{
case '+': ans = addition(op2, op1);
break;
}
s2.push(ans);
}
i++;
}
System.out.println("Answer is "+s2.pop());
}
publicstaticvoidpfeval(字符串exp)
{
堆栈s2=新堆栈();
int i=0;
BigInteger ans=BigInteger.valueOf(0);
biginger op1=biginger.valueOf(0);
biginger op2=biginger.valueOf(0);
而(i='0')&(exp.charAt(i)请看这一行:
(long)s2.pop()
然后,返回,使用s2.push()
看看你是否能找出问题所在:>看这一行:
(long)s2.pop()
然后,返回,使用s2.push()
然后看看你是否能发现问题:>你应该像下面那样进行铸造
op1 = (BigInteger) s2.pop();
op2 = (BigInteger) s2.pop();
Stack<BigInteger> s2 = new Stack<BigInteger>();
op1 = s2.pop();
op2 = s2.pop();
堆栈s2
已经包含biginger类型的对象,因此需要使用biginger
类型强制转换它
我建议你使用泛型集合,而不是像这样声明
Stack s2 = new Stack();
您可以定义如下:
op1 = (BigInteger) s2.pop();
op2 = (BigInteger) s2.pop();
Stack<BigInteger> s2 = new Stack<BigInteger>();
op1 = s2.pop();
op2 = s2.pop();
您应该按如下所示进行casting
op1 = (BigInteger) s2.pop();
op2 = (BigInteger) s2.pop();
Stack<BigInteger> s2 = new Stack<BigInteger>();
op1 = s2.pop();
op2 = s2.pop();
堆栈s2
已经包含biginger类型的对象,因此需要使用biginger
类型强制转换它
我建议你使用泛型集合,而不是像这样声明
Stack s2 = new Stack();
您可以定义如下:
op1 = (BigInteger) s2.pop();
op2 = (BigInteger) s2.pop();
Stack<BigInteger> s2 = new Stack<BigInteger>();
op1 = s2.pop();
op2 = s2.pop();
使堆栈通用
Stack<BigInteger> s2= new Stack<>();
使堆栈通用
Stack<BigInteger> s2= new Stack<>();
@user2785784如果您觉得有用,请将其标记为答案。@user2785784如果您觉得有用,请将其标记为答案。