我找不到逻辑算法来查找数组中两个连续索引之间的最大差异。当我在代码中使用该方法时,我的客户端页面给出了一个错误,指出我有一个越界异常。有什么建议么?如果您需要更多代码,请询问。
//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
和temps[i+1]
当 i 等于 temps.length -1(循环的最后一次迭代)时,i+1 将等于 temps.length。这意味着当数组有 10 个元素时,您正在尝试访问 array[10]。但数组只包含 0 到 9 作为索引。
改变i < temps.length
至i < temps.length-1
将解决问题..
关于java - 查找数组中两个连续元素之间的最大差异时出现 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21339000/