【发布时间】:2018-04-14 13:58:13
【问题描述】:
我已经搜索了几个 SOF 线程,但似乎找不到我正在寻找的答案。他们中的大多数都提供了超出我迄今为止所学范围的代码的答案。
我已经尝试了很多不同的方法,但无法让它按照我需要的方式工作。
程序应该获取给定的数组,读取它,找到给定的 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 课程中的一项作业,我们还没有学习列表(我在谷歌搜索中偶然发现的答案之一),所以这对我来说不是一个选择。
现在,它应该输出: [this, is, is, of, call]
目前正在输出:[this, is, null, example, of]
我们将不胜感激任何和所有的帮助!
【问题讨论】:
-
您可能想使用
.equals而不是.contains。如果你使用.contains,你的方法也会从数组中删除"the dog"、"absinthe"等。
标签: java arrays string methods