2010-07-28 58 views
0

當BigInteger大於Integer.MAX_VALUE時,我正在綁定引發異常。它不會允許我爲指數情況拋出異常。我不確定如何在biginteger值太大而無法傳入BigInteger.pow()方法時拋出異常。BigInteger.pow()與BigInteger

在此先感謝。

這裏是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(); 
} 
+1

可能的重複[你如何提高Java BigInteger的BigInteger的力量,而不做模運算?](http://stackoverflow.com/questions/2839262/how-do-you-raise-a-java -biginteger-the-power-of-biginteger-without-doing-mod) – finnw 2011-01-30 21:11:49

回答

0

它是書面的方式,它應該拋出ArithmeticException("Negative Exponent Error")如果指數大於Integer.MAX_VALUE更大。當你嘗試時會發生什麼?

+0

沒有任何反應是我遇到的問題。它只是執行,我得到了一個非常長的結果,如100 +整數值 – Karl 2010-07-28 03:57:44

+0

我明白了。我使用的變量是倒退的。所以我設置的值超過了Integer.MAX_VALUE,但在測試中使用了另一個值,所以它永遠不會拋出異常。 謝謝 – Karl 2010-07-28 04:18:42

+0

不,這不是整個故事,請看下面。 – EJP 2010-07-28 04:52:31

0

您按照錯誤的順序彈出堆棧。指數將位於堆棧的頂端,而不是尾數。你在減法,除法和模數方面有同樣的問題,也不會因爲加法和乘法的方式做同樣的事情。在任何情況下,它應該是b = stack.pop();那麼a = stack.pop()。如果你將堆棧聲明爲Stack stack = new Stack(),那麼你不需要所有這些類型轉換。