0

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

//我试过改原来的函数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.
4

1 回答 1

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

于 2019-07-03T05:06:19.940 回答