索引4超出长度3的范围。对于联合数组

时间:2019-07-03 05:01:59

标签: java arrays foreach stringindexoutofbounds

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

///我尝试更改原始函数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.

1 个答案:

答案 0 :(得分:1)

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

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

因此,您在if中的unionArrays语句始终为false