[英]How to count the number of times a string appears in an array without using maps?
我試圖計算一個字符串在數組中出現的次數,但是我不能使用任何類型的Map。 根據我的研究,我嘗試了以下方法,希望它能起作用:
int count = Collections.frequency(strings, search);
但是,當我在運行程序時遇到錯誤時。 該錯誤是一個Null Pointer Exception錯誤,我不確定如何解決該錯誤或發生原因。 關於我的代碼有什么問題的任何想法嗎?
編輯:這是我的完整代碼。 我找不到問題所在。 也許其他人可以找到它導入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;
}
}
您可以通過數組進行線性搜索
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);
在使用strings
之前,請對strings
進行null和大小檢查:
if (strings != null && strings.size() > 0) {
int count = Collections.frequency(strings, search);
}
如果size()
返回的數字大於0,則意味着您的strings
包含一些東西,您可以對其執行frequency()
。
查看http://www.tutorialspoint.com/java/util/collections_frequency.htm
有一個很好的使用頻率的例子(Collection c,Object o);
如果集合中的值之一為null,則可能發生nullpointerexception。 您確定排他性就在您的頻率上嗎?
這是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 == null
和包含null
元素的c
。 當c == null
時,它將拋出NullPointerException
的唯一情況。
另外,從文檔中:
頻率
公共靜態int頻率(集合c,對象o)
拋出:
- NullPointerException-如果c為null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.