我無法找到邏輯算法來查找數組中的兩個連續索引之間的最大差異。當我在我的代碼中使用該方法時,我的客戶頁面給了我一個錯誤,說我有一個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
一旦'i'等於'temps.length - 1'(最後一次迭代),您正在嘗試爲'temps.length'編制索引,因爲您正在執行'i + 1',導致您的異常。它編譯了 – gparyani