为什么我得到 - ArrayIndexOutOfBoundsException: 5?

我有两个排序数组。我需要将它们连接到一个新的排序数组中:


    int[] arr1 = {1,2,3,6,8};

    int[] arr2 = {4,5,9,12,208,234};

    printArr(allSort(arr2,arr1));

}


public static int[] allSort(int[] arr, int[] arr3) {


    int[] newArr = new int[arr.length + arr3.length];


    int j = 0;

    int k = 0;


    for (int i = 0; i < newArr.length - 1; i++) {

        if(j == arr3.length){

            newArr[i] = arr[k];

            k++;

        }

        if(k == arr.length){

            newArr[i] = arr3[j];

            j++;

        }

        if(arr[k] > arr3[j]){

            newArr[i] = arr3[j];

            j++;

        } else if (arr[k] < arr3[j]) {

            newArr[i] = arr[k];

            k++;

        }

    }

    return newArr;

}

我试图构建一个长度等于两个数组加在一起的长度的数组,然后在其上运行一个循环。


但是,此代码返回错误:AArrayIndexOutOfBoundsException: 5。


侃侃尔雅
浏览 147回答 3
3回答

MYYA

只需像这样在两个 if 条件中添加 continue,if(j == arr3.length){&nbsp; newArr[i] = arr[k];&nbsp; k++;&nbsp; continue;}if(k == arr.length){&nbsp; newArr[i] = arr3[j];&nbsp; j++;&nbsp; continue;}所以不管怎样,另一个循环已经完成,这就是我们迭代并添加所有值的原因,这样它就不需要检查所有其他条件,所以我们可以跳过它。还,for (int i = 0; **i < newArr.length**; i++)由于您正在检查“<”。

函数式编程

这ArrayIndexOutOfBoundsException()是一个异常,它的基本意思是在某些时候您试图访问具有非法索引的数组元素。在某些时候查看您的代码后,这里是索引的值:在循环中,您arr[k]使用 k = 5进行调用if(arr[k] > arr3[j]),这arr是一个长度为 5 的数组,因此最大索引为 4,这就是为什么您会遇到越界异常的原因。

神不在的星期二

您的主要问题是第一个阵列完成时的控制。我对您的代码进行了一些调整,现在可以正常工作了。public static void main(String[] args) {&nbsp; &nbsp; int[] arr1 = { 1, 2, 3, 6, 8 };&nbsp; &nbsp; int[] arr2 = { 4, 5, 9, 12, 208, 234 };&nbsp; &nbsp; int[] newArr = allSort(arr1, arr2);&nbsp; &nbsp; for (int i = 0; i <= newArr.length - 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(" " + newArr[i]);&nbsp; &nbsp; }}public static int[] allSort(int[] arr1, int[] arr2) {&nbsp; &nbsp; int j = 0;&nbsp; &nbsp; int k = 0;&nbsp; &nbsp; boolean endArr1 = false;&nbsp; &nbsp; int[] newArr = new int[arr1.length + arr2.length];&nbsp; &nbsp; for (int i = 0; i <= newArr.length - 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (arr1[k] < arr2[j] && !endArr1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("k: " + k + " " + arr1.length);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newArr[i] = arr1[k];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(k < arr1.length-1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; k++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; endArr1 = true;&nbsp; &nbsp; &nbsp; &nbsp;} else if (arr2[j] < arr1[k]&nbsp; || endArr1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("j: " + j + " " + arr2.length);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;newArr[i] = arr2[j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(j < arr2.length-1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;j++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }&nbsp; &nbsp; return newArr;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java