2011-04-21 2 views
0
try{ 
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 
      System.out.println(" Enter the Amount of articles to be ordered."); 
      amount = reader.readLine(); 

      if(amount.trim().isEmpty()){ 
       System.out.println("Amount Entered is Empty"); 
      } 

      for(int count=0;count<amount.length();count++){ 
       if(!Character.isDigit(amount.charAt(count))){ 
        throw new NumberFormatException(); 
       } 
      }    
      order.validateAmount(amount); 
     }catch(NumberFormatException numbere){ 
      System.out.println("Either Number format is uncorrect or String is Empty, Try Again."); 
    } 

위의 코드는 빈 문자열 예외와 잘못된 숫자 데이터 예외에 대한 단일 println() 문을 제공합니다. 원하지 않는 예외입니다. 두 가지 예외에 대해 별도의 println() 문을 원합니다. 얻는 방법?별도의 예외 진술을 제공해야합니다. 1. 빈 문자열 및 2. 유효한 숫자 데이터

답변

1
  1. 당신은 예를 NumberFormatExceptionIllegalArgumentException를 들어, 두 가지 예외를 사용하고 두 개의 서로 다른 catch을 -clauses 할 수있는 중.

    ... 
        if (amount.isEmpty()) 
         throw new IllegalArgumentException(); 
        ... 
    
    } catch (NumberFormatException numbere) { 
        System.out.println("Either Number format is uncorrect, Try Again."); 
    } catch (IllegalArgumentException empty) { 
        System.out.println("String is empty, Try Again."); 
    } 
    
  2. 다른 메시지과 같은 예외하지만 을 사용

    try { 
        BufferedReader reader = new BufferedReader(new InputStreamReader(
          System.in)); 
        System.out.println(" Enter the Amount of articles to be ordered."); 
        String amount = reader.readLine(); 
    
        if (amount.trim().isEmpty()) { 
         System.out.println("Amount Entered is Empty"); 
        } 
    
        if (amount.isEmpty()) 
         throw new IllegalArgumentException("String is empty."); 
    
    
        for (int count = 0; count < amount.length(); count++) 
         if (!Character.isDigit(amount.charAt(count))) 
          throw new IllegalArgumentException("Number format incorrect."); 
    
        order.validateAmount(amount); 
    } catch (IllegalArgumentException e) { 
        System.out.println(e.getMessage() + " Try again."); 
    } 
    
  3. 또는, 수 롤 자신의 Exception 예외가 있다면라는 두 개의 서로 다른 생성자 및 플래그 잘못된 번호 또는 빈 문자열로 인해

+0

나는 이것이 가능할 것이라고 생각한다. –

+0

다른 대안에 대해 자세히 설명해주기를 바랍니다. – aioobe

1

빈 문자열이 '예상'예외이기 때문에 내가 예외를 사용하지만 그것을 확인하지 않을 :

if (amount.trim().equals(string.empty)) 
{ 
    System.out.println("string empty"); 
} 
else 
{ 
    //do your other processing here 
} 

공허함에 대한 또 다른 검사는 당신이 정말로 원하는 경우 amount.trim().length == 0

것 예외를 사용하는 방법 :

if(amount.trim().equals(string.empty)) 
{ 
    throw new IllegalArgumentException("Amount is not given"); 
} 

및 catch()

} 
catch(NumberFormatException numbere) 
{ 
} 
catch(IllegalArgumentException x) 
{ 
    // Amount not given 
} 
+0

'String.isEmpty' 메소드가 있습니다. 빈 문자열과 비교할 필요가 없습니다. – aioobe

+0

InvalidArgumentException을 처리하기 위해 가져올 항목. 나는 javadoc을 찾지 못했습니다. –

+0

아무 것도. 'java.lang' 패키지에 있습니다. (자동으로 JVM에 의해 임포트됩니다.) – aioobe