2014-01-24 42 views
0

我無法找到邏輯算法來查找數組中的兩個連續索引之間的最大差異。當我在我的代碼中使用該方法時,我的客戶頁面給了我一個錯誤,說我有一個outofbounds異常。有什麼建議麼?如果你需要更多的代碼,那就問問。ArrayIndexOutOfBoundsException找到數組中的兩個連續元素之間的最大差異

//method returning the largest change between two consecutive days 
    public int NetChange() 
    { 
     int BiggestNet = temps[0] - temps[1]; 
     for(int i = 0; i < temps.length; i++) 
     { 
     if((temps[i] - temps[i+1]) > BiggestNet) 
     { 
      BiggestNet = (temps[i] - temps[i+1]); 
     } 
     } 
     return BiggestNet; 
    } 

錯誤:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 
    at Forecast.NetChange(Forecast.java:105) 
    at Forecast.toString(Forecast.java:120) 
    at ForecastClient.main(ForecastClient.java:12 
+1

一旦'i'等於'temps.length - 1'(最後一次迭代),您正在嘗試爲'temps.length'編制索引,因爲您正在執行'i + 1',導致您的異常。它編譯了 – gparyani

回答

2

變化

for(int i = 0; i < temps.length; i++) 

for(int i = 0; i < temps.length - 1; i++) 

temps.length會給你不使用從零開始計數的數組的長度,但它通過基於零的索引訪問。所以如果我= temps.length - 1,那實際上是數組中的最後一個元素。如果你然後嘗試訪問會比你的數組更長並因此出界的臨時數[i + 1]。

+0

,謝謝 – PatGreens

3

問題是這兩個代碼片斷... i < temps.lengthtemps[i+1]

當i等於-1 temps.length這是最後一次迭代循環,i + 1將等於temps.length。這意味着當數組有10個元素時,你正試圖訪問數組[10]。但數組只包含0到9作爲索引。

改變i < temps.lengthi < temps.length-1會解決這個問題..

1

由於您的循環變量i去從0temps.length - 1(因爲<),你必須在身體

temps[i+1] 

i需要的temps.length - 1值(它可以採取的最後一個值),當你到達

temps[temps.length - 1 + 1] 

是一樣的

temps[temps.length] 

它會引起Excepction,因爲只能從0length - 1訪問一個數組。

如何解決這個問題?您可以嘗試減少1i的最後一個值。換句話說:

for(int i = 0; i < temps.length - 1; i++) 
1

臨時工[I + 1]是問題

時,我是最後一個索引,i + 1將給予例外。

相關問題