当BigInteger大于Integer.MAX_VALUE时,我想要抛出异常。它不允许我为exponent案例抛出该异常。当biginteger值太大而无法传递给BigInteger.pow()方法时,我不确定如何让它抛出异常。
提前致谢。
这是toPostfix方法:
public BigInteger evalPostfix(String postfix){
BigInteger a, b;
Stack stack = new Stack();
for(int i=0; i<postfix.length(); i++){
if(this.isOp(postfix.charAt(0)))
throw new ArithmeticException("Malformed Postfix Expression");
switch(postfix.charAt(i)){
case '+':
a = (BigInteger)stack.pop();
b = (BigInteger)stack.pop();
stack.push(b.add(a));
break;
case '-':
a = (BigInteger)stack.pop();
b = (BigInteger)stack.pop();
stack.push(b.subtract(a));
break;
case '*':
a = (BigInteger)stack.pop();
b = (BigInteger)stack.pop();
stack.push(b.multiply(a));
break;
case '/':
a = (BigInteger)stack.pop();
b = (BigInteger)stack.pop();
if(a == BigInteger.valueOf(0)){
throw new ArithmeticException("Cannot divide by 0");
}else{
stack.push(b.divide(a));
}
break;
case '%':
a = (BigInteger)stack.pop();
b = (BigInteger)stack.pop();
stack.push(b.mod(a));
break;
case '^':
a = (BigInteger)stack.pop();
b = (BigInteger)stack.pop();
if(b.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0)
throw new ArithmeticException("BigInteger value is too large");
stack.push(a.pow(b.intValue()));
break;
default:
if(this.numbers.get(postfix.substring(i, i+1)) == null)
throw new NullPointerException(postfix.substring(i, i+1) + " is not mapped to any value");
stack.push(this.numbers.get(postfix.substring(i,i+1)));
}
}
return (BigInteger)stack.pop();
}
答案 0 :(得分:0)
如果指数大于ArithmeticException("Negative Exponent Error")
,它的编写方式应该抛出Integer.MAX_VALUE
。你尝试的时候会发生什么?
答案 1 :(得分:0)
你以错误的顺序弹出堆栈。指数将位于堆栈的顶部,而不是在尾数下。你在减法,除法和模数方面遇到同样的问题,并且以相同的方式进行加法和乘法也不会有什么坏处。在每种情况下,它应该是b = stack.pop();然后a = stack.pop()。如果您将堆栈声明为Stack stack = new Stack(),则不需要所有这些类型转换。