它不断抛出异常ArrayIndexOutOfBound。我无法弄清楚哪里出了问题

时间:2016-03-30 05:05:42

标签: java arrays exception indexoutofboundsexception

所以我试图运行以下代码,将两个已排序的数组合并为一个已排序的数组。但它不断给我一个arrayIndexOutOfBound例外。我想防止这种异常。

public class SortArray {

    public static void main(String[] args){
        SortArray sa = new SortArray();
        // create two arrays
        int[] a = {1, 2, 3, 4, 5};
        int[] b = {6, 7, 8, 9, 10};
        int[] merge = sa.mergeArray(a, b);
        for (int i = 0; i < merge.length; i++) {
            System.out.print(merge[i] + " ");
        }

    }       
    public int[] mergeArray(int[] arr1, int[] arr2){
        int arr1Length = arr1.length;
        int arr2Length = arr2.length;
        int[] merge = {}; // the merged array
        int i, j;
        int k = 0;
        // when the index of both arrays are within array length
        for (i = 0, j = 0; i < arr1.length && j < arr2Length;) {
            if (arr1[i] < arr2[j]) {
                merge[k] = arr1[i];
                i++;
                k++;
            }else if (arr1[i] > arr2[j]) {
                merge[k] = arr2[j];
                j++;
                k++;
            }
        }
        // when arra1 is the remaining array
        if (i < arr1Length) {
            merge[k] = arr1[i];
            i++;
            k++;
        }
        // when array2 is the remaining error
        if (j < arr2Length) {
            merge[k] = arr2[j];
            j++;
            k++;    
        }
        return merge;
    }

}

任何人都可以帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您没有正确调整merge数组的大小。

int[] merge = {};

创建零长度int[](并且Java数组具有 固定 长度)。你想要像

这样的东西
int[] merge = new int[arr1Length + arr2Length];