2014-02-13 4 views
0

이 메서드는 정수를 배열에 추가합니다. 나는 부정적인 정수와 문자 같은 것들을 잡기 위해 입력을 잡는 시도를하는 법을 알아야한다. 나는 그것을하는 법을 알 수 없다. 내가 어떻게 할까?Java의 범위 및 알파 오류 캐치 시도

private static int[] addInt (int[] ara, Scanner kb) { 
    int[] newAra = new int[ara.length + 1]; 
    for(int i = 0; i < ara.length; i++) { 
     newAra[i] = ara[i]; 
     } 
    System.out.println("Enter new integer:"); 
    newAra[newAra.length-1] = kb.nextInt(); 
    selectionSort(newAra); 
    return newAra; 
    } 
+0

, 당신의 방법

int value = kb.nextInt(); if (value < 0) throw new IllegalArgumentException(); else newAra[newAra.length-1] = kb.nextInt(); 

과 코드에 음수에 대한 예외를 던지기의 예입니다 ... 사용 배열을 삭제하는 대신 arraylist를 사용하여 새로운 한 시연 시간을 만들고 이전 값으로 채우기 – codeMan

답변

2

int은 음수를 지원합니다. 음수에 대한 예외를 원한다면 직접 생성해야합니다. 귀하의 코드는 Scanner 클래스의 InputMismatchException을 던집니다.이 클래스는 스캐너의 다음 토큰이 정수의 정규 표현식과 다른 단어로 일치하지 않는 경우 throw됩니다. 문자. 성능이 우려에도 릴 비트 인 경우

여기 아래는

try { 
    my_int_array = addInt(my_int_array, scanner); 
} 
catch (InputMismatchException ime) { 
    // tell that it's not a digit - number 
} 
catch (IllegalArgumentException iae) { 
    // tell that it's a negative input 
} 
catch (Exception e) { 
    // to catch all other exceptions from the Scanner class like IllegalStateException ... 
} 
+0

"기본적으로 int 데이터 유형은 32 비트 부호있는 2의 보수 정수이며 최소값이 -2^31이고 최대 값 2^31-1의 값 " – Brian

+0

클래스 NegativeNumberException이 존재하지 않습니다. – user3242445

+0

오, 알았어. 편집을 봤어. – user3242445