尝试计算两个整数之间的最小距离时出错

时间:2012-04-29 20:44:35

标签: java arrays algorithm

我正在尝试计算排序数组中任意两个数字之间的最短距离。我正在使用下面的算法测试它,但我直接在下面得到以下错误;这表明我的数组超出界限,显然它试图访问一个不在数组长度内的索引?不知道为什么我在for循环中检查长度。有没有人有线索?

public static void getSmallestDistance(int[] integersCount)
{

    int index = 0;

    for(int i = 1; i < integersCount.length; i++  )
    {
        if( Math.abs(integersCount[index] - integersCount[index + 1]) >
        Math.abs( integersCount[i] - integersCount[i + 1]))//line 73 were error is
        {
            index = i;
        }



    }
    System.out.println(index);
}

我收到以下错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000
at ClosestPair.getSmallestDistance(ClosestPair.java:73)
at ClosestPair.main(ClosestPair.java:57)

5 个答案:

答案 0 :(得分:2)

问题是数组的长度为integersCount.lengthi的最大值为integersCount.length - 1,但您使用i+1索引数组,这是超出范围的

因此,您需要将i从0或1(根据需要)运行到integersCount.length - 2,这意味着i < integersCount.length - 2i <= integersCount.length - 1

答案 1 :(得分:1)

for(int i = 1; i < integersCount.length; i++  )

应该是

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

这是因为你这样做:

integersCount[i + 1])

当(当然)当我处于最大值时抛出ArrayIndexOutOfBound

正如其他一些回答者所指出的那样,这是因为java数组是从0到长度为1的索引,并且在for循环的最后一次迭代中,我将是length-1而i + 1因此会过大索引。

答案 2 :(得分:0)

循环中的

integersCount[i + 1]会导致"ArrayIndexOutOfBoundsException"

例如,如果你有10个项目,并且在for循环的最后一次运行中,我将是9而i + 1将是10,这将超出界限。

答案 3 :(得分:0)

尝试将(int i = 1; i&lt; integersCount.length; i ++)更改为 for(int i = 0; i&lt; integersCount.length; i ++)

我相信数组从地址0开始,因此您需要从内容总数中减去1以获得最后添加的数字。

修改

将integersCount.length-1更改为正确的integersCount.length,因为它应该低于添加的数量,而不是低于添加的数量 - 1 ..

答案 4 :(得分:0)

for(int i = 1; i < integersCount.length; i++  )
{
  if( Math.abs(integersCount[index] - integersCount[index + 1]) >
      Math.abs( integersCount[i] - integersCount[i + 1]))//line 73 were error is 
      {
        index = i;
      }

i = integersCount.length - 1是数组的末尾时,你试图使用integersCount[i + 1],这显然超出了数组的界限。