【问题标题】:Index 4 out of bounds for length 3. For Union Array索引 4 超出长度 3 的范围。对于联合数组
【发布时间】:2019-07-03 05:01:59
【问题描述】:

//每当我运行代码时,它总是给我同样的错误。我不明白为什么。联合数组函数的循环也没有完全循环,可能是字符串索引超出范围的问题。

//我已经尝试改变原来的函数isNumberInArray,但还是不行。

package HW;

public class HW_5 {


public static boolean isNumberInArray(int number_check, int array[]) {
    for (int value : array) {
        value -= 1;
        if (number_check == array[value]) {
            return true;
        }
    }
    return false;
}


public static int highestlength(int array_1[]) {
    int max = array_1[0];
    for (int counter = 1; counter < array_1.length; counter++) {
        if (array_1[counter] > max) {
            max = array_1[counter];
        }
    }
    return max; 
}


public static int [] unionArrays(int [] array_1, int [] array_2) {
    int array_index_counter = 0;
    int highest_1 = highestlength(array_1);
    int highest_2 = highestlength(array_2);
    int[] union_array = new int[array_1.length + array_2.length];
    if (highest_1 > highest_2) {
    for (int value_1 : array_1) {
        if (isNumberInArray(value_1, array_1) && isNumberInArray(value_1, array_2)) {
            union_array[array_index_counter] = value_1;
            array_index_counter += 1;
        } else {
            for (int value_2 : array_2) {
                if (isNumberInArray(value_2, array_1) && isNumberInArray(value_2, array_2)) {
                    union_array[array_index_counter] = value_2;
                    array_index_counter += 1;
                }
            }
        }
    }
}
    printArray(union_array);
    return union_array;
}



public static void printArray(int array[]) {
    for (int value : array) {
        System.out.print(value + " ");
    }
    System.out.println();
}


public static void main(String[] Args) {
    int list_1[] = {1, 2, 3};
    int list_2[] = {1, 3, 5};
    System.out.println(isNumberInArray(0, list_1));
    System.out.println(unionArrays(list_1, list_2));
}
}


I expected the output to be 1 2 3 5, but the actual output is 0 0 0 0.

【问题讨论】:

    标签: java arrays foreach stringindexoutofbounds


    【解决方案1】:

    首先,isNumberInArray 中的循环很奇怪,试试

    public static boolean isNumberInArray(int number_check, int array[]) {
        for (int value : array) {
            if (number_check == value) {
                return true;
            }
        }
        return false;
    }
    

    可能正因为如此,您在unionArrays 中的if 语句总是false

    【讨论】:

    • 什么都没发生。 :(
    • 您也可以使用if (highest_1 &gt; highest_2) {,但数组的大小相同。哦,我看到它只是获得最大值。 Array2 有最大值,所以不会进入这个if 语句
    • 我摆脱了那部分。现在我得到了,1 3 0 0,比以前更好。耶
    • 你想做两个循环(不是嵌套的)。每个阵列一个。尝试使用调试器并单步执行您的代码。另见Rubber Ducking
    • 由于我是新来的溢出,它说它不会在公共场合显示,但它确实考虑到了。
    猜你喜欢
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多