簡體   English   中英

嘗試計算兩個整數之間的最小距離時出現錯誤

[英]Getting an error when trying to computer the smallest distance between two integers

我正在嘗試計算排序數組中任何兩個數字之間的最短距離。 我正在使用下面的算法進行測試,但是下面直接顯示了以下錯誤; 這說明我的數組超出范圍,因此很顯然它正在嘗試訪問不在數組長度內的索引? 不知道為什么,因為我在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)

問題是數組的長度是integersCount.lengthi的最大值是integersCount.length - 1 ,但是您使用i+1來索引數組,這超出了范圍。

因此,您需要將i從0或1(根據需要)一直運行到integersCount.length - 2 ,這意味着i < integersCount.length - 2i <= integersCount.length - 1

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

應該

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

因為您這樣做:

integersCount[i + 1])

當我達到最大時哪個(當然)拋出ArrayIndexOutOfBound

正如其他一些答復者指出的那樣,這是因為java數組是從0到length-1的索引,並且在for循環的最后一次迭代中,我將是length-1,因此i + 1將是一個太大的索引。

循環中的integersCount[i + 1]導致"ArrayIndexOutOfBoundsException"

例如,如果您有10個項目,並且在for循環的最后一次運行中,i將為9,而i + 1將為10,這將超出范圍。

嘗試將for(int i = 1; i <integersCount.length; i ++)更改為for(int i = 0; i <integersCount.length; i ++)

我相信數組從地址0開始,所以您需要從內容總數中減去1以獲得最后添加的數字。

編輯

將integersCount.length-1更改為正確的integersCount.length,因為它應該比og的加法數低,而不是比加法的數-1 ..

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] ,它顯然超出了數組的范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM