2014-12-07 137 views
-1

我正在嘗試編寫一個程序來將任意數字的值等同於任何權力,我想爲小於零的指數實現異常處理,這是我成功完成的,同時還爲異常處理該值太大而無法輸出,即無窮大。Infinity的Java異常處理

public class power 
{ 
// instance variables - replace the example below with your own 
public static double Power(double base, int exp) throws IllegalArgumentException 
{ 

    if(exp < 0){ 

     throw new IllegalArgumentException("Exponent cannot be less than zero"); 

    } 
    else if(exp == 0){ 
     return 1; 

    } 


    else{ 
     return base * Power(base, exp-1); 

    } 
} 

} 

繼承人的測試類:

public class powerTest 
{ 
public static void main(String [] args) 
{ 
    double [] base = {2.0, 3.0, 2.0, 2.0, 4.0 }; 
    int [] exponent = {10, 9, -8, 6400, 53}; 

    for (int i = 0; i < 5; i++) { 

    try { 
     double result = power.Power(base[i], exponent[i]); 
     System.out.println("result " + result); 
    } 
    catch (IllegalArgumentException e) { 
     System.out.println(e.getMessage()); 
    } 
    catch (ArithmeticException e) { 
     System.out.println(e.getMessage()); 
    } 
    } 
} 
} 

繼承人測試的輸出:

result 1024.0 
result 19683.0 
Exponent cannot be less than zero 
result Infinity 
result 8.112963841460668E31 

我的問題是

其中包含功能電源我的繼承人功率等級我怎樣才能通過ArithmeticException處理某些事情而得到「結果無窮大」來說別的東西沿着「浮點溢出」的線?

在此先感謝。

+0

目前還不清楚你在問什麼。如果結果是無限的,你想拋出異常嗎?你想知道如何檢查結果是無限的嗎? – Radiodef 2014-12-07 22:40:27

+0

結果無限時拋出異常 – 2014-12-07 22:40:58

+0

清楚地知道如何拋出異常。也許你可以編輯你的問題來澄清你遇到的問題。 – Radiodef 2014-12-07 22:41:48

回答

0

不知道這是你在找什麼,但你可以用一個if語句測試無窮/溢出以及:在您的情況

if(mfloat == Float.POSITIVE_INFINITY){ 

    // handle infinite case, throw exception, etc. 
} 

所以,你會做這樣的事情:

public static double 
Power(double base, int exp) throws IllegalArgumentException 
{ 

    if(exp < 0){ 
     throw new IllegalArgumentException("Exponent less than zero"); 
    } 
    else if(exp == 0){ 
     return 1; 
    } 
    else{ 

     double returnValue = base * Power(base, exp-1); 
     if(returnValue == Double.POSITIVE_INFINITY) 
      throw new ArithmeticException("Double overflowed"); 

     return returnValue; 

    } 
} 
+0

而不是mfloat我需要一個方程式被執行後代表該值的變量,這就是我被卡住的地方 – 2014-12-07 22:45:55

+0

謝謝!這就是我所要求的謝謝你的幫助,接受了你的回答 – 2014-12-07 22:50:49

1

當你捕獲異常,這裏

catch (ArithmeticException e) { 
    System.out.println(e.getMessage()); 
} 

只是做

System.out.println("Floating point Overflow") 

以及(如果你想添加更多的)這個說法

這或更換第一印像你說的那樣,「你得到的結果是無窮大的」,通過ArithmeticException處理來說出別的東西「

+0

你指的是測試類,它不告訴我如何通過電源類捕捉它,我沒有在你的測試類中使用try和catch – 2014-12-07 22:39:02

+0

,你正在使用try catch – committedandroider 2014-12-07 22:39:40