从数组中删除第一个或最后一个索引而不出现"Out of Bounds"错误



我被指派创建一个程序,在它的一个方法中,我必须提示用户输入他们想要删除的索引值。我的问题是,当我试图删除索引0,然后我得到一个ArrayIndexOutOfBoundsException在索引-1。所以为了解决这个问题,我尝试了i <= currentSize + 1,它修复了索引0的问题,但是最后一个索引,我得到了一个越界错误,因为currentSize比它们的数组大小多一个。任何帮助都会很感激。

//This method drops the value of a selected index in the array.
private static void Drop ()
{
     int m =0;
     System.out.println("Choose an index that you would like to drop the value of:");    
     if(input.hasNextInt())
     {
         m = input.nextInt();
         for(int pos = 0; pos < values.length; pos++)
         {
             if(pos == m)
             {
                 for(int i = pos+1; i<=currentSize+1; i++)
                 {
                     values[i-1]= values[i];
                     values[i]=0;
                 }
                 currentSize--;
                 break;
             }
             else if(pos == 0)
             {
                 System.out.println("ERROR: There is not an index at the specified location.");
             }  
         }
     }
     else
     {
         System.out.println("ERROR: Please input a integer value.");
     }
}

这是一种高效而紧凑的方法:

private static void drop(int[] arr, int index, int currentSize) {
    System.arraycopy(arr, index + 1, arr, index, currentSize - index - 1);
}

这有效地将数组元素向左移动,从指定索引+ 1开始,直到currentSize。它适用于任何有效的索引,例如,对于一个大小为3的数组,它适用于索引0、1、2。它不检查边界,因此,在本例中,索引-1或3将抛出ArrayIndexOutOfBoundsException

使用这个函数,您可以将代码简化为:

private static void mainInputLoop() {
    System.out.println("Choose an index that you would like to drop the value of:");
    if (input.hasNextInt()) {
        index = input.nextInt();
        drop(values, index, currentSize--);
    } else {
        System.out.println("ERROR: Please input a integer value.");
    }
}

你可以使用System.arrayCopy()来简化你的代码

相关内容

最新更新