我的教授在本周的期中考试中提出了一个我很困惑的复习问题:
编写一个方法,该方法被赋予一个二维(粗糙)字符串对象数组,并返回一个二维(粗糙)字符串对象数组,其中所有的空项都已被删除。例如,如果原始数组具有数据(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;
}我知道我需要计算每一行中的空值的数量,并从字符串数组“数组”(我知道的坏名字)的每一行的总长度中减去这个值。我想,如果我为一个一维数组做了一个方法,它会帮助我更好地理解逻辑:
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衣衫褴褛的数组方法,任何澄清将不胜感激!而且,我不相信我能导入任何东西(至少不应该导入),而且这又一次只是一个复习问题,所以我没有强调要得到一个答案,只是试图理解它背后的逻辑。
发布于 2015-12-15 15:51:50
你可以这样做:
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], []]。
编辑:更新了一些评论.
https://stackoverflow.com/questions/34293326
复制相似问题