我必须创建一个频率表,表示单词出现在句子中的次数。我试图用2个阵列来完成这个,但每次跟踪它时,这些词都不会进入频率表。
boolean found = false;
for (int y = 0; y < numWordsInArray; y++)
{
found = arrayOfWords[y].equals(word);
if(found)
{
numTimesAppeared[y]++;
}
if (!found) //it's not already found
{
//add the word to the array of words
arrayOfWords[numWordsInArray] = word;
numWordsInArray++;
}
}
当我运行此循环时:
for(int x = 0; x < 10; x++)
{
System.out.println(arrayOfWords[x]);
}
跟踪数组,得到10个空格的输出。
链接到整个程序:http://pastebin.com/F4t6yCkD
答案 0 :(得分:0)
使用HashMap
代替数组numTimesAppeared
。
示例代码:
private Map<String, Integer> freqMap = new HashMap<String, Integer>();
public void statFreq(String[] words) {
for(String word : words) {
Integer freq = freqMap.get(word);
if(freq == null) {
freqMap.put(word, 1);
} else {
freqMap.put(word, freq + 1);
}
}
}
答案 1 :(得分:0)
尝试使用哈希表
Hashtable<String, Integer> words = new Hashtable<String, Integer>();
使用
Integer count = words.get (word)
和
if (count == null) {
words.put (word, 1);
else
words.put (word, count.intValue () + 1);