ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

Kim yeonhee·2024년 12월 4일

Error

목록 보기
1/6

에러 발생

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

프로그래머스 문제를 풀다가 별로 작성한 것도 없는 코드에 오류가 발생했다!?


코드

public static int[] solution(int[] num_list) {
		int[] answer = {};
        for(int i = 0; i < num_list.length; i++) {
        	answer[i] = num_list[i];
        }
        
        return answer;
    } 

위 코드를 main에서 실행하면 위와 같은 에러가 발생한다.
이 에러는 인덱스가 배열의 크기보다 크거나 음수가 나오면 발생시키는 예외이다.
다시 보니 배열 선언도 안하고 값을 대입했다.

어처구니없는 실수..



수정된 코드

 	public static int[] solution(int[] num_list) {
        int[] answer = new int[7];
        for(int i = 0; i < num_list.length; i++) {
        	answer[i] = num_list[i];
        }
        
        return answer;
    }




배열의 크기를 지정해주면 정상적으로 실행된다.
이런 실수는 다시는 하지말자....!

0개의 댓글