替换2D数组中的某些单词



方法plant()StringString[][]的2D数组作为其输入。数组中的字符串不应被输入的单词替换。

public static void plant(String veggie, String[][] garden) {
String[] veggies =
{"broccoli", "cactus", "carrot", "corn", "potato", "pumpkin"};
// YOUR CODE HERE in RED
}

2D阵列:

String[][] garden = {
{"cactus", "carrot", "potato", "fish taco", "broccoli"},
{"wombat", "corn", "mr bautista", "tomato", "pumpkin"},
{"potato", "carrot", "toast", "mr bautista", "potato"},
{"broccoli", "broccoli", "yellowfin tuna", "orc", "cactus"}};

示例:

// the word pumpkin is what we are using
// to replace the words we don't want
plant("pumpkin", garden);

这应该是输出:

{{"cactus", "carrot", "potato", "pumpkin", "broccoli"},
{"pumpkin", "corn", "pumpkin", "pumpkin", "pumpkin"},
{"potato", "carrot", "pumpkin", "pumpkin", "potato"},
{"broccoli", "broccoli", "pumpkin", "pumpkin", "cactus"}};

注意:方法plant()不返回任何内容。

这应该会对您有所帮助:

public static void plant(String veggie, String[][] garden) {
String[] veggies =
{"broccoli", "cactus", "carrot", "corn", "potato", "pumpkin"};
// YOUR CODE HERE in RED
HashSet<String> set = new HashSet<>(Arrays.asList(veggies));
for (int i = 0; i < garden.length; ++i)
for (int j = 0; j < garden[i].length; ++j)
if (!set.contains(garden[i][j]))
garden[i][j] = veggie;
System.out.println(Arrays.deepToString(garden));
}

然而,输出格式略有不同。不过我相信你能应付的。

最新更新