当BigInteger大于Integer.MAX_VALUE时,我会抛出一个异常。它不允许我在指数情况下抛出异常。当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();
}发布于 2010-07-28 11:47:59
按照它的编写方式,如果指数大于Integer.MAX_VALUE,它应该抛出ArithmeticException("Negative Exponent Error")。当你尝试它的时候会发生什么?
发布于 2010-07-28 12:48:57
您按错误的顺序弹出堆栈。指数将在堆栈的顶部,而不是在尾数之下。你在减法、除法和模数上也有同样的问题,对于加法和乘法也不会有什么坏处。在任何情况下,都应该是b= stack.pop();然后是a= stack.pop()。如果你将堆栈声明为stack Stack = new Stack(),你就不需要所有这些类型转换了。
https://stackoverflow.com/questions/3349766
复制相似问题