简体   繁体   中英

How to properly check if two jagged arrays are the same size?

I am having trouble checking if two jagged java arrays are the same size. My function isn't returning the correct result. The hw problem I'm working on states that the function should return true if both arrays are null or are the same size, and should return false if the only one of the array's is null or if they have a different size.

I have tried executing the code to see what boolean value is returned, however the console outputs nothing.

static boolean arraySameSize(int[][] one, int[][] two) {    
    boolean value = false;
    if (one == null && two == null) {
        value = true;
    } else if ((one == null && two != null) || (two == null && one != null)) {
        value =  false;
    } else {
        int count = 0;
        int count2 = 0;
        for (int i = 0; i < one.length; i++) {
            for (int j = 0; j < one[i].length; j++) {
                count++;
            }
        }
        for (int i = 0; i < two.length; i++) {
            for (int j = 0; j < two[i].length; j++) {
                count2++;
            }
        }
        if (count == count2) {
            value = true;
        } else {
            value = false;
        }
    } 
    return value;
}

I expect the output to be true if both array's are null or are the same size, false otherwise. I am getting an error from the auto-grader stating the following:

java.lang.AssertionError: Incorrect result: expected [false] but found [true]

What should I adjust to ensure that value has the correct value when it's returned?

try this.

static boolean arraySameSize(int[][] one, int[][] two) {
    if (one == null && two == null) return true;
    if (one == null || two == null) return false;
    if (one.length != two.length) return false;
    for (int i = 0, size = one.length; i < size; ++i) {
        int[] oneRow = one[i];
        int[] twoRow = two[i];
        if (oneRow == null && twoRow == null) continue;
        if (oneRow == null || twoRow == null) return false;
        if (oneRow.length != twoRow.length) return false;
    }
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM