我想計算一個字符串出現在數組中的次數,但我不能使用任何類型的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;
}
}
'如果c是null.' [源(http://www.tutorialspoint.com/java/util/collections_frequency.htm)(C在該示例中是'串的NullPointerException --This被拋出') –
該數組正在用作參數,並以另一種方法創建。爲什麼它是空的?下面是更多的代碼: 'code'公共靜態INT countValues(字符串搜索,列表字符串){ \t \t \t \t詮釋計數= Collections.frequency(字符串,搜索); \t \t \t \t \t \t \t \t返回計數; \t}'code' –
qwerty5683
請不要通過評論發佈代碼,編輯你的問題:)更清潔,更容易閱讀 –