2015-04-06 47 views
1

我想計算一個字符串出現在數組中的次數,但我不能使用任何類型的Map。從我的研究,我嘗試以下期待它的工作:如何計算字符串在不使用地圖的情況下出現在數組中的次數?

int count = Collections.frequency(strings, search); 

然而,當我運行程序時得到了一個錯誤。該錯誤是一個空指針異常錯誤,我不知道如何解決這個問題或爲什麼發生。關於我的代碼有什麼問題的任何想法?

編輯:這是我的完整代碼。我找不到問題所在。也許別人可以找到它 import java.util。*;

公共類Lab9 {

public static void main(String[] args){ 
    Scanner kb = new Scanner (System.in); 
    String name = null; 
    List<String> strings =null; 
    System.out.println("How many strings do you want to enter?:"); 
    int size = kb.nextInt(); 

    List<String> String = getStrings(size,name); 
    System.out.println(String); 
    System.out.println("What string would you like to search for?:"); 
    String search = kb.next(); 

    int numofTimes = countValues (search,strings); 
    System.out.print("That word appears "+numofTimes+" times in the array."); 


} 
public static List<String> getStrings(int size,String name) { 
    Scanner kb = new Scanner (System.in); 
    int count = 0; 
    List<String> strings = new ArrayList<String>(); 
    while (count != size) { 
     System.out.println("Enter a string:"); 
     name = kb.nextLine(); 
     strings.add(name); 
     count = count + 1; 
      } 

return strings; 

} 
public static int countValues (String search, List<String> strings){ 

    int count = Collections.frequency(strings , search); 



    return count; 
} 



} 
+1

'如果c是null.' [源(http://www.tutorialspoint.com/java/util/collections_frequency.htm)(C在該示例中是'串的NullPointerException --This被拋出') –

+0

該數組正在用作參數,並以另一種方法創建。爲什麼它是空的?下面是更多的代碼: 'code'公共靜態INT countValues(字符串搜索,列表字符串){ \t \t \t \t詮釋計數= Collections.frequency(字符串,搜索); \t \t \t \t \t \t \t \t返回計數; \t}'code' – qwerty5683

+0

請不要通過評論發佈代碼,編輯你的問題:)更清潔,更容易閱讀 –

回答

0

做一個零和尺寸檢查上strings使用它之前:

if (strings != null && strings.size() > 0) { 
    int count = Collections.frequency(strings, search); 
} 

如果size()返回大於0的數,這意味着你的strings有東西在裏面您可以在其上執行frequency()

1

您可以通過陣列

String strings[] = {"A","B",null,"C","A",null}; // the array contains nulls 
    String search = "A"; 
    int count = 0; 
    for (int i = 0;i< strings.length ;i++) 
    { 
     if(strings[i] != null) 
     { 
      if(strings[i].equals(search)) 
      { 
       count++; 
      } 
     }     
    } 
    System.out.println(count); 
0

這是Collections.frequency()代碼做線性搜索:

public static int frequency(Collection<?> c, Object o) { 
    int result = 0; 
    if (o == null) { 
     for (Object e : c) 
      if (e == null) 
       result++; 
    } else { 
     for (Object e : c) 
      if (o.equals(e)) 
       result++; 
    } 
    return result; 
} 

正如你所看到的,它能夠處理o == nullcnull元素。唯一的情況是它會拋出NullPointerException的時候是c == null

此外,從文檔:

頻率

公共靜態INT頻率(集合C,對象o)

拋出:

  • 的NullPointerException - 如果c爲空
相關問題