오류노트

[코딩 오류 노트] 배열 선언 실수, 배열 인덱스 범위 초과

망고고래 2023. 10. 16. 17:46

1. 배열 선언 실수

오류 메시지

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

Syntax error, insert ". class" to complete Expression

The type of the expression must be an array type but it resolved to Class<Integer>

c cannot be resolved to a variable

 

코드

int[c] = new int[10];

 

해결

int[]c = new int[10];

배열 길이가 대괄호 안에 들어가는 것과 헷갈리지 않도록 한다.

 

 

 

2. 배열 인덱스 범위 초과

오류 메시지

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:

Index 5 out of bounds for length 5

 

코드

int[][] test = new int[6][5];
for(int i=0; i<test.length; i++)
{
    for(int k = 0; k<test.length; k++)
    {
         test[i][k] = i*k;
         System.out.println(test[i][k]);
    }
}

*코드에 오류 밑줄이 그이지는 않음

 

해결

for(int k = 0; k<test[i].length; k++)

열의 길이는 test.length가 아니라 test[i].length와 같이 표현한다.

*i는 행