[英]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.