2016-07-14 26 views
-2

我需要從字符串變量中刪除像貓和魚這樣的字符串值。 我做了一些示例Java代碼來刪除字符串值。使用Java刪除字符串值

public static void deleteAccNode(String refId){ 
    String refId [] = {"Fish","Dog","Dolphins","rowboat","Fish","sailor","Cat","cats","Cat","Fish", 
     "Fish","Tree","Fishes","Cat","Cat","CAT","Cat"}; 

     try { 
      System.out.println("GeneralLength"+refId.length); 
      for (int n = refId.length; n <= 1;){ 
      if(refId.equals("Cat")){ 
       System.out.println("cat : :"+refId); 
       How to remove the String value?remove("Cat"); 
       }else if(refId.equals("Fish")){ 
        System.out.println("Fish : :"+refId); 
        How to remove the String value?remove("Fish"); 
       } 
      n--; 
      } 
     } catch (NullPointerException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

需要的輸出:狗,海豚,划艇,水手,貓,樹,魚,CAT 但是,電流輸出:NullPointerException異常

+2

所以...什麼阻止你? – Stultuske

+0

究竟是什麼問題? –

+1

「魚」「狗」「海豚」「划艇」「魚」「水手」「貓」「貓」「貓」「魚」 +「魚」 「樹」,「魚」,「貓」,「貓」,「貓」,「貓」;'從未見過這樣的事情。我不認爲它編譯? – ifly6

回答

1

這只是一種方式,是有很多,你可以剛剛google了這個。

String[] stringArray = { "Cat", "Fish", "CatFish", "Elephant" }; 
    final List<String> newArrayList = new ArrayList<>(); 
    for (final String string : stringArray) 
    { 
    if (!(string.equals("Cat") || string.equals("Fish"))) 
    { 
     newArrayList.add(string); 
    } 
    } 

    stringArray = (String[]) newArrayList.toArray();