【问题标题】:It keeps throwing an exception ArrayIndexOutOfBound. I cannot figure out where went wrong [duplicate]它不断抛出异常 ArrayIndexOutOfBound。我无法弄清楚哪里出了问题[重复]
【发布时间】:2016-07-17 22:37:20
【问题描述】:

所以我试图运行以下代码,将两个排序数组合并为一个排序数组。但是它一直给我一个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;
    }

}

有人可以帮我吗?谢谢!

【问题讨论】:

    标签: java arrays exception indexoutofboundsexception


    【解决方案1】:

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

    int[] merge = {};
    

    创建一个零长度int[](Java 数组有一个固定 长度)。你想要类似的东西

    int[] merge = new int[arr1Length + arr2Length];
    

    【讨论】:

    • 谢谢!由于我是新来的,我向所有认为我的问题编辑非常不恰当的人道歉。我以后会改进的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多