2017-01-30 539 views
0

我試圖通過將現有元素複製到新數組中刪除空元素。但是,即使我在for循環內初始化它,新數組的初始化也會導致我的返回值爲空。從數組(Java)中刪除空元素

public String[] wordsWithout(String[] words, String target) { 
    for(int i = 0; i < words.length; i = i +1){ 
     String store[] = new String[words.length]; 
     if (words[i] == target){ 
      words[i] =""; 
     } 
     else if(words[i] != target){ 
      words[i] = store[i]; 
     }  
    } 
    return words; 
} 
+1

你需要'store [i] = words [i];',然後返回'store'。 –

+0

[this]的可能重複(http://stackoverflow.com/questions/9785336/how-to-check-if-array-indexes-are-empty-and-if-so-check-the-next)。請檢查,這可能會幫助你。 –

+0

您正在爲每次迭代創建store []。 store []總是一個長度爲[]長度的數組,但只保存非空值 – baao

回答

0

您不應該使用==運算符比較字符串。這是不正確的,因爲字符串是對象。使用.equals()方法,這應該解決您的問題。你的代碼的

其餘部分是相當混亂,很難理解你想要達到的:在創建新的字符串數組store在循環迭代每一次,然後分配其null(默認)值words[i]。你應該詳細說明你的代碼和算法。

+0

好的,但不等於什麼? – Ruben

+0

同樣的方式'!字[i]中。等於(目標)'。 – Andremoniy

+0

好吧,我試過你的方法,結果是一樣的 – Ruben

0

有幾件事我把它放在下面。希望你能從中得到幫助。

  1. String store[] = new String[words.length]實例化的 字符串數組,但它不與任何非 空值實例的任何元件。缺省值爲null,因此這是一個空字符串數組。
  2. (words[i] != target)應改爲

    (!字[I] .equals(目標))

0

實際上,我不知道你想達到什麼,但如果你想刪除空字符串出你的陣列,你可以用流和過濾器做在Java 8這樣的:

String[] objects = Arrays.stream(new String[]{"This","", "will", "", "", "work"}).filter(x -> !x.isEmpty()).toArray(String[]::new); 
0

要檢查平等使用.equals()方法,即string1.equals(字符串2),並檢查不相等ÿ你可以使用相同的方法,但不要使用(!)操作符i-e。 !string1.equals(字符串2)。您應該在循環之外聲明商店數組,因爲在每次迭代中它都會創建一個新對象並使用商店。在其他條件下,這個商店[i] =詞[i]。

1

數組是不可變的如此的尺寸保持不變,你需要創建一個新的Array 所以,如果你的舊陣列,你仍然有null元素

的大小創建一個新的磁盤陣列的基礎。如果你想使用數組只需要計算數組中的非空元素來獲取新數組的大小。它只是更容易使用一個List/ArrayList

public String[] wordsWithout(String[] words, String target) { 
    List<String> tempList=new ArrayList<String>(); 
    for(int i = 0; i < words.length; i = i +1){ 

     if (words[i]!=null||words[i].trim().length()>0){ 
      tempList.add(words[i]); 
     } 

    } 
    return (String[]) tempList.toArray(); 
} 
+0

好吧,我得到它的邏輯,但你可以建議一個方法,而不使用(列表)。現在我面臨的問題是複製數組的初始化。我無法初始化for循環外部或for循環內,因爲我只會返回一個空值的數組 – Ruben

+0

@Ruben這是一樣的數組,只需刪除列表,並使用數組 – AxelH

+0

如果您使用一個數組需要先計算現有數組中已填充的元素,然後將其用作新數組的大小,或者如果使用現有數組的大小,則仍然會有空元素 –