2013-03-07 45 views
0

我的代码如下所示从txt文件中取出所有单词,并在旁边打印数字1(count)。我的程序的目的是把所有的单词都看作是它的做法,但如果它是重复的,我不希望它打印出我希望它找到它的匹配的单词,并将其添加到它的数目中。查找数组中的重复项并将其添加到计数中

Scanner in = new Scanner(new File(filename)); 
int i = 0; 
int n = 1; 
String w = ""; 
String txt = ""; 

while ((in.hasNext())) { 
    w = in.next() ; 
    wrd[i] = w; 
    num[i] = n; 
    i++; 
    txt = wrd[i]; 

} 
+0

一个建议 - ** AVOID **使用'Scanner'从'File'中读取。 'FileReader'对你做了什么错误? – SudoRahul 2013-03-07 16:09:43

回答

4

您要使用地图:

Map<String, Integer> map = new HashMap<String, Integer>(); 
... 

while (in.hasNext()) { 
    String w = in.next(); 

    if (map.containsKey(w)) { // Already in the map 
     map.put(w, map.get(w) + 1); // Increment the counter 
    } else { // First time w is found, initialize the counter to 1 
     map.put(w, 1); 
    } 
} 

基本上,地图(要算的话在这里)的值(当前出现的#相关联的关键字字)。 containsKey检查某个值是否与给定键相关联,get检索该值(如果有)并且put设置新值。

相关问题