[英]How to remove certain elements from my array in my Java code
我正在为班级使用以下编码提示:您的任务是编写一个具有以下签名的方法:
public static String[] removeFromArray(String[] arr, String toRemove)
该方法应返回与arr内容相同的字符串数组,除非没有出现toRemove字符串。 例如,如果您的方法被下面的代码调用
String[] test = {“this”, “is”, “the”, “example”, “of”, “the”, “call”};
String[] result = removeFromArray(test, “the”);
System.out.println(Arrays.toString(result));
它应该生成以下输出:
[this, is, example, of, call]
注意:测试程序将为您的方法传递arr和toRemove的值-您不应从方法内部的用户那里读取这些值。 另外,您必须使用上面要求的签名来编写此方法,才能获得信用。 您无需编写调用该方法的代码,而只需编写方法本身。 提示:因为创建数组时必须指定数组的长度,所以可能需要
通过输入数组进行两次循环:一次计数toRemove字符串的出现次数,因此
您可以创建具有适当大小的新数组,并用一秒钟的时间将所有其他字符串复制到新数组中。
我的代码中的所有内容都可以正常工作,但是我必须打印出新数组的最后一部分不起作用,我知道我已经将其缩小了,因此可以正确打印出,但是我无法使该部分正常工作。 我知道我必须摆脱null,但我不知道如何。 而且我的代码必须适用于任何数组,而不仅仅是我的测试用例。 一些帮助或建议真的很好。 非常感谢你!!! :)这是我的代码:
public static void main(String[] args) {
String[] test = {"this", "is", "the", "example", "of", "the", "call"};
String[] remove = removeFromArray(test, "the");
System.out.println(Arrays.toString(remove));
}
public static String[] removeFromArray(String[] arr, String toRemove) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(toRemove)) {
count++;
}
}
String[] result = new String[arr.length - count];
//for (int i = 0; i < arr.length; i++) {
// if(!arr[i].equals(toRemove)){
// result[].equals(arr[i]);
//}
//}
return result;
}
您的方法看起来还不错,看起来您注释的代码正在尝试为新数组分配错误的方法
您应该使用result[i] = arr[i] ;
而不是result[].equals(arr[i]);
最后做:
String[] result = new String[arr.length - count];
int k = 0;
for (int i = 0; i < arr.length; i++) {
if(!toRemove.equals(arr[i])){
result[k] = arr[i];
k++;
}
}
return result;
您的最后一部分应该是将值逐个分配给数组。
int j = 0;
for (int i = 0; i < arr.length; i++) {
if(!toRemove.equals(arr[i])){
result[j++] = arr[i];
}
}
它要求您返回一个不包含给定单词的新String数组。 遍历数组并添加不等于给定单词的单词。
public static String[] removeFromArray(String[] arr, String toRemove){
ArrayList<String> words = new ArrayList<>();
for(String s : arr)
if(!s.equals(toRemove))
words.add(s);
return words.toArray(new String[0]);
}
由于创建后无法更改数组大小,因此请使用ArrayList存储单词,然后以数组形式返回。
我知道您是编程新手,因此给出的解决方案非常好。
但是,使用Java,通常会使用这些库。 在这种情况下,是收藏库。 如果您使用的是Java 8,则应采用以下方法:
public static String[] removeFromArray(String[] arr, String toRemove) {
// create a List and fill it with your items
ArrayList<String> list = new ArrayList();
Collections.addAll(list, arr);
// remove the items that are equal to the one to be removed
list.removeIf(s -> toRemove.equals(s));
// transfer back to array
return list.toArray(new String[list.size()]);
}
然后,有Java 8流,这将使
public static String[] removeFromArray(String[] arr, String toRemove) {
return Arrays.stream(arr) // create stream from array
.filter(s -> !toRemove.equals(s)) // filter out items
.toArray(String[]::new); // create array from stream
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.