Java ArrayIndexOutOfBoundsException,同时查找数组中两个连续元素之间的最大差异

Java ArrayIndexOutOfBoundsException,同时查找数组中两个连续元素之间的最大差异,java,arrays,for-loop,indexoutofboundsexception,Java,Arrays,For Loop,Indexoutofboundsexception,我找不到逻辑算法来查找数组中两个连续索引之间的最大差异。当我在代码中使用这个方法时,我的客户端页面给了我一个错误,说我有一个outofbounds异常。有什么建议吗?如果你需要更多的代码,那就问吧 //method returning the largest change between two consecutive days public int NetChange() { int BiggestNet = temps[0] - temps[1]; f

我找不到逻辑算法来查找数组中两个连续索引之间的最大差异。当我在代码中使用这个方法时,我的客户端页面给了我一个错误,说我有一个outofbounds异常。有什么建议吗?如果你需要更多的代码,那就问吧

//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;
     } 

问题是这两段代码<代码>i
temps[i+1]

当i等于temps.length-1(循环的最后一次迭代)时,i+1将等于temps.length。这意味着当数组有10个元素时,您正试图访问数组[10]。但数组只包含0到9作为索引

i
更改为
i
将解决此问题。

更改

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

for(int i=0;i

temps.length
将为您提供不使用基于零的计数的数组长度,但它是通过基于零的指示符访问的。因此,如果i=temps.length-1,这实际上是数组中的最后一个元素。如果您尝试访问temp[i+1],它将比您的数组长,因此超出范围。

因为循环变量
i
0
变为
temps.length-1
(因为
temps[i+1])


当i是最后一个索引时,i+1将给出异常。

一旦
i
等于
temps.length-1
(最后一次迭代),您将尝试索引
temps.length
,因为您正在执行
i+1
,导致异常。
for( int i = 0; i < temps.length; i++ )
for( int i = 0; i < temps.length - 1; i++ )
temps[i+1]
temps[temps.length - 1 + 1]
temps[temps.length]
for(int i = 0; i < temps.length - 1; i++)