我已经查看了几个SOF线程,但似乎找不到我需要的答案。大部分提供的代码超出了我目前所学范围的答案。
我尝试了很多不同的方法,但无法使它按照我的需求工作。
该程序应该读取给定的数组,查找给定的toRemove项,并重新打印不包含toRemove项的数组。
我认为我的问题在于removeFromArray方法。
这是我Java课程上的一个作业,我们还没有学习List(在我的谷歌搜索中找到的答案之一),所以这对我来说不是一个选项。目前应该输出: [this, is, example, of, call],但实际上它输出的是: [this, is, null, example, of]。非常感谢任何形式的帮助!
我尝试了很多不同的方法,但无法使它按照我的需求工作。
该程序应该读取给定的数组,查找给定的toRemove项,并重新打印不包含toRemove项的数组。
我认为我的问题在于removeFromArray方法。
public static void main(String[] args)
{
String[] test = {"this", "is", "the", "example", "of", "the", "call"};
String[] result = removeFromArray(test, "the");
System.out.println(Arrays.toString(result));
}
public static String[] removeFromArray(String[] arr, String toRemove)
{
int newLength = 0;
for(int i = 0; i < arr.length; i++)
{
if(arr[i].contains(toRemove))
{
newLength++;
}
}
String[] result = new String[arr.length-newLength];
for(int i = 0; i < (result.length); i++)
{
if(arr[i].contains(toRemove))
{
}
else
{
result[i] = arr[i];
}
}
return result;
}
这是我Java课程上的一个作业,我们还没有学习List(在我的谷歌搜索中找到的答案之一),所以这对我来说不是一个选项。目前应该输出: [this, is, example, of, call],但实际上它输出的是: [this, is, null, example, of]。非常感谢任何形式的帮助!
.equals
而不是.contains
。如果你使用.contains
,你的方法也会从数组中删除“the dog”,“absinthe”等内容。 - Andy