2016-06-04 2 views
-1

NumberFormatException의 번호 (순서)를 처리 할 수있는 방법이 있습니까? Double 피연산자 []를 사용하여 계산기를 만들었습니다. 아래처럼 오류가 언제 발생했는지 기록하고 싶습니다. "2 + k"입력을 넣으면 "operand [1]에 잘못된 입력이 있습니다."라는 메시지가 나타납니다. 나올거야. 어떻게해야합니까?java에서 NumberFormatException을 어떻게 처리해야합니까?

+0

당신은 입력이 계산기로 전달하기 전에 숫자 인 것을 확인 할 수 있습니다. 문자열이 숫자인지 확인하기 위해 SO를 검색하면 많은 예제를 찾을 수 있습니다. –

+0

'calculate()'메서드는 피연산자를 double로 변환합니다. 예외를 별도로 catch하고 원하는 명시 적 메시지로 다시 throw 할 수 있습니다. '새로운 NumberFormatException을 던지기 (String.format ("피연산자 [% d]에 잘못된 입력이 있습니다.", operandIndex));'. 그러면 여기서'NumberFormatException'을 잡아 메시지를 출력 할 수 있습니다. 바울의 대답처럼 입력 내용의 유효성을 직접 확인하지 않아도됩니다. 그냥 'double'에 넣고 예외를 잡아라. – Arjan

답변

0

먼저, NumberFormatException(String) 생성자를 사용하여 MyCalculator.calculate() 방법에 예외를 던질 때 이제 메시지를 전달할 수 있습니다 라인

System.out.println(e.getMessage()); 

으로 라인을

System.out.println("operand[] has the wrong input."); 

를 교체합니다.

calculate(String expression) 
{ 
    //validate input code 
    //... 

    //if operand 0 not valid 
    throw new NumberFormatException("operand 0 has the wrong input"); 

    //if operand 1 not valid 
    throw new NumberFormatException("operand 1 has the wrong input"); 

    //rest of calculate method 
} 
0

아마도 새로운 예외를 정의 할 수 있습니다. 예를 들어 어떤 피연산자가 올바르지 않은 경우와 같이 더 구체적인 계산에 대한 정보를 포함 할 수있는 예 : CalculatorException과 같이 또는 IllegalOperandException과 같이 하나 더 예외를 정의 할 수도 있습니다. CalculatorException까지 확장 할 수 있습니다. 그리고 나서 calculate 메서드는 CalculatorException을 던지는 것으로 선언 될 수 있습니다. 결론적으로, 아이디어는 문제의 도메인과 더 관련이있는 정보를 제공하기 위해 예외의 새로운 계층 구조를 정의하는 것입니다.

그리고, 코드가 너무 수 :

try { 
    System.out.println("result: " + MyCalculator.calculate(expression)); 
    System.out.println(); 
} catch(CalculatorException e) { 
    System.out.println(e.getMessage()); 
}