2014-12-07 4 views
-1

어떤 숫자의 값과도 동등한 프로그램을 작성하려고합니다. 성공적으로 수행 한 지수가 0보다 작고 예외 처리를 구현한다고 가정합니다. 값이 너무 커서 무한대로 출력 할 수 없습니다.무한대에 대한 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); 

    } 
} 

} 

Heres는 테스트 클래스 : heres는

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 

내 질문은 함수 전원을 포함

을 heres 내 전력 등급 뭔가를 처리 ArithmeticException 통해 뭔가 다른 말을 "결과 무한"얻을 수 있습니다. "Floating point Overflow"라인을 따라? 사전에

감사합니다.

+0

당신이 묻는 것이 명확하지 않습니다. 결과가 무한 경우 예외를 throw 하시겠습니까? 결과가 무한인지 확인하는 방법을 알고 싶습니까? – Radiodef

+0

결과가 무한 할 때 예외를 throw –

+0

예외를 throw하는 방법을 잘 알고 있습니다. 아마도 문제를 편집하여 문제가 무엇인지 명확히 할 수 있습니다. – Radiodef

답변

0
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; 

    } 
} 
: 이것이 당신이 찾고있는,하지만 당신은뿐만 아니라 if 문 무한대/오버 플로우를 테스트 할 수있는 경우확실하지 : 당신이 뭔가를 그래서

if(mfloat == Float.POSITIVE_INFINITY){ 

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

을 상황에서 할 것

+0

대신 mfloat가 필요합니다 방정식이 실행되면 값을 나타내는 변수이며 그 값이 붙어 있습니다. –

+0

감사합니다! 그게 다 네가 고맙다는 이유 다. 도움이된다. 대답을 받아 들였다. –

1

여기에 예외를 잡을 때이 문

이를 함께 첫 번째 인쇄를하거나 교체 (당신이 더 추가 할 경우)

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

은 단지뿐만 아니라

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

을 당신이 말했듯이 ArithmeticException 처리를 통해 "무한 결과를 얻습니다"라고 말한 것처럼 "

+0

당신은 파워 클래스를 통해 잡는 법을 알려주지 않는 테스트 클래스를 언급하고 있습니다. 나는 테스트 클래스에서 –

+0

을 잡으려고하지 않고 try catch를 사용하고 있습니다. – committedandroider