2013-11-25 71 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

既然你開始你的counter11for循環爲6迭代中,counter1在最後一次迭代這給ArrayIndexOutOfBoundsException變成7。因爲你array的大小爲7,且您嘗試使用array[counter1]counter1變爲7

在陣列最大可訪問索引始終array.length - 1,你的情況來訪問索引7array[6]是最後一個可訪問索引你的數組。

1

counter1初始值是1counter1值將是7通過i=6。但是沒有數組的索引。

0

陣列對於大小7定義和迭代僅進行6次......所以異常

0

當你增加countercounter1,設置counter1counter1是準確counter+1。當counterarray.length-1時,您的counter1等於array.length7

正如你目的是計算兩個相鄰整數的GCD爲什麼不直接使用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