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

标签 java arrays indexoutofboundsexception

我被分配创建一个程序,在其方法之一中,我必须提示用户输入他们想要删除其值的索引。我的问题是,当我尝试删除索引 0 时,我得到 ArrayIndexOutOfBoundsException在索引-1处。所以为了解决这个问题,我尝试了 i <= currentSize + 1这解决了索引 0 的问题,但是对于最后一个索引,我收到了越界错误,因为 currentSize 比数组大小大 1。任何帮助,将不胜感激。

//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.");
    }
}

关于java - 删除数组中的第一个或最后一个索引而不出现 "Out of Bounds"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32915312/

相关文章:

java - 为什么错误的路径注释不会使 Jersey 的 REST API 崩溃?

php - 从数组中选择特定元素

python - 当数字中没有字母时,bytearray.fromhex 不会转换

Java:修改不带参数的变量

java - 将 servlet 自动部署到 glassfish 后出现 404

java - 可以使用嵌入式 jetty 以编程方式设置上下文阀和 Realm 吗?

javascript - 使用 for 循环通过 array.length 向后循环 javascript 数组

java - DialogFragment 上的 ArrayIndexOutOfBoundsException 崩溃

java - 不知道为什么JAVA数组会越界

Java 在编辑 observableList 时抛出 IndexOutOfBounds