오류해결

[자바] ArrayIndexOutOfBoundsException 에러

wjxor 2021. 9. 5. 03:35
반응형

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)

 

2. 코드

class Solution {
	public long[] solution(long x, int n) {
		long[] answer = {};

		for (int i = 0; i < n; i++) {

			answer[i] = x * (i + 1);
		}

		return answer;
	}
}

 

3. 해결

- 구글링을 해보니 인덱스가 배열의 크기보다 크거나 음수가 나온다면 예외를 발생시킨다.

- 에러코드를 자세히 살펴보니 0의 크기라고 그러길래 코드를 자세히 살펴보니 배열도 제대로 선언을 하지않고,

  배열을 사용했다...

class Solution {
	public long[] solution(int x, int n) {
		long[] answer = new long[n];

		for (int i = 0; i < n; i++) {

			answer[i] = x * (i + 1);
		}

		return answer;
	}
}

- 그래서 이렇게 수정을 해주었다.

- 어이없는 실수....ㅠㅠㅠ

반응형