【发布时间】:2014-02-15 19:41:48
【问题描述】:
我找不到一个逻辑算法来查找数组中两个连续索引之间的最大差异。当我在我的代码中使用该方法时,我的客户端页面给了我一个错误,说我有一个 outofbounds Exception。有什么建议?如果您需要更多代码,请询问。
//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,导致你的异常。
标签: java arrays for-loop indexoutofboundsexception