[JAVA] ArrayIndexOutOfBoundsException 에러

hjeu·2023년 1월 4일
0

에러일지

목록 보기
1/7
  1. 오류

프로그래머스 문제를 푸는데 이런 오류가 났다.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at Solution.solution(Unknown Source)
at SolutionTest.lambda$main$0(Unknown Source)

at SolutionTest$SolutionRunner.run(Unknown Source)
at SolutionTest.main(Unknown Source)

  1. 원인
class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = {};
        for(int i=0; i < num_list.length; i++) {
            answer[i] = num_list[num_list.length-i-1];
        }
        return answer;
    }
}

이렇게 실행을 했는데 자꾸 오류가 났고, 구글링을 해보니인덱스가 배열의 크기보다 크거나 음수가 나온다면 예외를 발생시킨다고 하더라... 프로그래머스에서 저대로 주길래 배열 선언이 된줄 알았는데 아니었다.

  1. 해결
class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = new int[num_list.length];
        for(int i=0; i < num_list.length; i++) {
            answer[i] = num_list[num_list.length-i-1];
        }
        return answer;
    }
}

배열 선언부분을 저렇게 배열 크기를 지정해주니 잘 돌아갔다!
잊지말자...너무 공부 안했다!

profile
기록하는 습관!

0개의 댓글