2013-11-25 6 views
0

어떤 이유로이 오류가 발생합니다.배열 인덱스가 경계를 벗어남 오류

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 
at Assignment25.main(Assignment25.java:80) 

public static void main (String[] args){ 
long[] array = new long[7]; 
for (int i = 0; i < 6; i++){ 
    int thefib = 39; 
    array[i] = fib(thefib); 
    thefib++; 
} 

int counter = 0; 
int counter1 = 1; 
for(int i = 0; i < 6; i++){ 
    long start = System.currentTimeMillis(); 
    gcd(array[counter], array[counter1]); 
    long end = System.currentTimeMillis(); 
    long time = end - start; 
    System.out.println("GCD time for " + (counter + 39) + " and " + (counter1 + 
     39) + " is " + time); 
    counter++; 
    counter1++; 
} 

counter = 0; 
counter = 1; 
for(int i = 0; i < 6; i++){ 
    long start1 = System.currentTimeMillis(); 
    gcd2(array[counter], array[counter1]); 
    long end1 = System.currentTimeMillis(); 
    long time1 = end1 - start1; 
    System.out.println("GCD2 time for " + (counter + 39) + " and " + (counter1 + 
     39) + " is " + time1); 
    counter++; 
    counter1++; 
    } 
} 

}

+2

이유는 당신이 배열 외부의 인덱스를 사용하는 것입니다. – m0skit0

답변

1

당신이 6 반복에 대한 귀하의 1에서 counter1for 루프를 시작하기 때문에, counter1ArrayIndexOutOfBoundsException주는 마지막 반복 7이된다. 당신의 array의 크기가 7이며 counter1은 7.

배열의 최대 접근 지수는 귀하의 경우, 항상 array.length - 1입니다 될 때 array[counter1]를 사용하여 인덱스 7에 액세스하기 위해 노력하고 있기 때문에, array[6]는 마지막 접근 인덱스 귀하의 배열. counter1

1

초기 값과 1counter1i=6 의해 7 될 것이다. 그러나 배열에 대한 인덱스가 없습니다.

0

배열의 크기는 7에 대해 정의되고 반복은 6 번 수행됩니다 ... 그래서 예외

0

당신이 countercounter1를 증가, 당신은 정확히 counter+1counter1counter1을 설정합니다. counterarray.length-1 일 때 counter1array.length과 같으며 이는 7입니다. 당신이 의도 인접한 두 정수의 최대 공약수를 계산하는 것이다으로

이유를 직접 i 자체를 사용하지 :

for(int i = 0; i < array.length -1 ; i++){ // <<---- array.length-1 = 6, i guess 
    long start1 = System.currentTimeMillis(); 
    gcd2(array[i], array[i+1]); 
    // other code 
관련 문제