2016-04-26 32 views
0

所以我正在做一個CS課程的作業,涉及使用hashmaps,我需要跟蹤一個單詞出現在頁面上的次數。哈希值中的值乘以15?

現在出於一些奇怪的原因,我遇到了最奇怪的錯誤,一切似乎正常工作,一切都存儲在地圖中,但是,當我打印出來測試時,地圖中的每個值乘以15.

成員僅出現8次,但我的輸出是120

雷丁僅出現32次,但我的輸出是480

下面是相關的代碼:

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

while (match.find()) { 
    String word = match.group().toLowerCase(); 
    Integer check = found.get(word); 

    if (check == null) { 
     found.put(word, 1); 
    } else { 
     found.put(word, check+1); 
    } 
} 
... 
for (Map.Entry<String, Integer> entry : found.entrySet()) { 
    String k = entry.getKey(); 
    Integer i = entry.getValue(); 

    System.out.println("Word: " + k + " \t\t\tFrequency: " + i); 

} 

有沒有人知道這裏會發生什麼?

編輯:於正則表達式和這樣的代碼:

String word_pattern = "[A-Za-z]{5,}"; 
String content = WebDoc.getBodyContent(url); 

Matcher match = Pattern.compile(word_pattern).matcher(content); 

如果問題出在這裏比我不明白爲什麼,因爲這符合我的老師的示例代碼,和他的樣品運行不有這個問題。

+1

你的正則表達式匹配太多了嗎? –

+0

相關代碼不在您發佈的代碼中。看到上面的評論... –

+0

嗯,這看起來[非常熟悉](http://stackoverflow.com/questions/36879295/sorting-maps-without-a-comparator-an-arraylist-or-a-treeset/36879435 #comment61324680_36879295)... – shmosel

回答

0

當使用match.group()時,您並不是只抓取所需匹配的單個實例。

考慮在第一個循環中輸出檢查的值,看看那裏發生了什麼。

+0

謝謝,這指出我在正確的方向,我想我知道如何解決這個問題。 – InstantRegret