2014-12-07 141 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