2015-10-15 44 views
0

因此,下面我試圖演示一下我的程序是如何使用僞代碼實現的一個有點現實的版本..所以我有一個hashmap。我打算閱讀一段文字,並且每當添加一個字母字符時就遞增;所以最終結果將是如果例如。 「doog」d = 1 o = 2 g = 1。HashMap計數值

它循環遍歷文本並返回值,但是它給了我每個字符的錯誤計算。我的代碼似乎完全有效,它計算的字符,但只是不等於它應該是= /如果有人有任何想法,爲什麼這是計算錯誤,然後請向我解釋。

while((text = something.readLine()) != null){ 

     for i = 0; i < text i++ 
     { 
      if (hash map already contains the key at text.charAt(i){ 
       continue; 
      }add the following to my hashmap(text.charAt(i), incrementer++); 
      } 
      else{ 
      add (text.charAt(i), incrementer); 
      } 
     } 
    } 
+6

請你分享一下實際的代碼嗎? –

+1

如果它已經包含密鑰,則需要增加計數並且不要繼續;''' – Siddhartha

+2

有些問題可能會導致僞代碼幫助提高可見性,提出一個無用的細節。情況並非如此,完整的代碼將只有更長的時間(比如'哈希映射已經包含密鑰')並且調試它對您更有用。 – Deltharis

回答

0

很難讀取您的僞代碼,但我認爲您在循環內增加了太多次。對於哈希映射中存在的每個評估,這可能使其錯過一個或兩個字符。只需增加for循環定義,它應該可以正常工作。

0

一個bug: continue語句:在java中它會跳轉到for循環,並且不會在hashmap中增加字符計數器,但它應該這樣做。

0

如果您的目的是計算字符串中字符的出現次數,主題行應該更加清晰。

public static Map<String, Integer> getOccurences(String string) { 
    Map<String, Integer> occurenceMap = new LinkedHashMap<>(); 
    String[] strArray = string.split(StringUtils.EMPTY); 
    int count = 0; 
    for(String str : strArray) { 
     if(occurenceMap.containsKey(str)) { 
      continue; 
     } 
     count = StringUtils.countMatches(string, str); 
     occurenceMap.put(str, count); 

    } 
    return occurenceMap; 
} 

沒有Apache Commons的替代版本。

public static Map<String, Integer> getOccurences(String string) { 
    Map<String, Integer> occurenceMap = new LinkedHashMap<>(); 
    String[] strArray = string.split(""); 
    int count = 0; 
    for(String str : strArray) { 
     if(occurenceMap.containsKey(str)) { 
      count = occurenceMap.get(str).intValue(); 
      count++; 
     } else { 
      count = 1; 
     } 
     occurenceMap.put(str, count); 

    } 
    return occurenceMap; 
}