2

我的教授本周为我们的期中考试提出了一个让我感到困惑的问题:

编写一个方法,给定一个 String 对象的二维(不规则)数组,并返回一个 String 对象的二维(不规则)数组,其中所有空条目都已删除。例如,如果原始数组有数据(NULL 表示空引用):

{"John", null, "Mary", "George", null},{null, "Pete", "Rick"},{null, null, null}};

您的方法生成的结果将是一个包含三行的二维数组。

{"John", "Mary", "George"},{"Pete", "Rick"},{}}; // last row will be empty

我的代码是:

public static String[][] removeNull2D(String[][] ragged) {
    int counter = 0;
    int nullCounter = 0;
    String[][] array; // isn't initialized

    // doesn't work I tested in debugger, need a way to shorten each row by the amount of null values it has
    for (int i = 0; i < ragged.length; i++) {
        for (int j = 0; j < ragged[i].length; j++) {
            if (ragged[i][j] == null) {
                nullCounter++;
                for (j = 0; j < ragged[i].length; j++) {
                    array = new String[ragged.length][ragged[i].length - nullCounter];
                }
            }
        }
    }
    // based off 1D array approach
    for (int i = 0; i < ragged.length; i++) {
        for (int j = 0; j < ragged[i].length; j++) {        
            if (ragged[i][j] != null) {
                array[i][counter++] = ragged[i][j];
            }
        }
    }
    return ragged;
}

我知道我需要计算每行中空值的数量,然后从字符串数组“array”的每行总长度中减去它(我知道的坏名字)。我想也许如果我为一维数组制作一个方法,它会帮助我更好地理解逻辑:

public static String[] removeNull1D(String[] a) {
    String[] array = new String[a.length - 1];
    int counter = 0;

    for (int i = 0; i < a.length; i++) {
        if (a[i] != null) {
            array[counter++] = a[i];
        }
    }
    a = array;
    return array;
}

仍然对如何将逻辑应用于 2D 参差不齐的数组方法感到困惑,任何澄清将不胜感激!另外,我不相信我可以导入任何东西(至少不应该),这再次只是一个审查问题,所以我并不强调要得到答案,只是试图理解它背后的逻辑。

4

1 回答 1

2

你可以这样尝试:

public static void main(String[] args) {
    String[][] ragged = { { "John", null, "Mary", "George", null }, { null, "Pete", "Rick" }, { null, null, null } };

    String[][] cleaned = new String[ragged.length][];
    for (int i = 0; i < ragged.length; i++) {
        cleaned[i] = clean(ragged[i]); // Apply clean method to each sub array.
    }

    System.out.println(Arrays.deepToString(cleaned));
}

private static String[] clean(String[] dirty) {
    int nonNullCount = 0;
    for (String string : dirty) {
        if (string != null) {
            nonNullCount++; // Count non-null Strings.
        }
    }
    String[] clean = new String[nonNullCount]; // Create array for non-null Strings.
    int cleanIndex = 0;
    for (String string : dirty) {
        if (string != null) {
            clean[cleanIndex] = string; // Insert only non-null String at index.
            cleanIndex++; // Only then update index.
        }
    }
    return clean;
}

对我来说似乎有点不雅,但目前我想不出一种方法来防止双循环clean(String[] dirty)

尽管如此,它还是[[John, Mary, George], [Pete, Rick], []]按需要输出。

编辑:更新了一些评论。

于 2015-12-15T15:51:50.337 回答