2017-05-29 3 views
1

私はスクールの割り当てをしています。これは、キー(この場合は文字タイプ)を配置するアルゴリズムと、 1に設定され、増分値としてマップに戻されます。 現在の文字が存在しない場合、私は 'current_character、1'のキーと値のペアを配置することになっています。このメソッドは単に新しいエントリをマップに追加し、値をインクリメントしません(その種類の最初のものと仮定します)。ここ はコードです:ここではJavaマップに文字が既に存在するかどうかに応じて追加する

private void calculateCharCountAlpha(){ 
    for(String current : lines){ 
     for(int i = 0, length = current.length(); i < length; i++){ // iterate through each character of each string 
      char currentKey = current.charAt(i); 

      if(! (charCountAlpha.containsKey(currentKey))){ // check if the map doesn't contain the current character at the current location in the current string 
       charCountAlpha.put(currentKey, 1); // place the current character into the map, with a value of 1 
      } // end of if 
      else{ 
       int val = charCountAlpha.get(currentKey); 
       val++; // add 1 to val 
       charCountAlpha.put(currentKey, val); // place the current character in the map, with a value that has been added to 1 
      } // end of else 
     } // end of for 
    } // end of for-each 

    /** Call calculateCharCountDescendingByCount */ 
    calculateCharCountDescendingByCount(); 

} // end of calculateCharCountAlpha() 

はcharCountAlphaです:

private TreeMap< Character, Integer > charCountAlpha = new TreeMap<>(); // this map stores the number of words, with their counts. Also stores the elements in order of key 

正直なところ、ここに私の最大の疑問は、 "これは正しくマップに要素を追加していますか?"、です。私は少しデバッグしていて、なぜ私の出力が奇妙なのかの問題を見ることができませんでした。私は出力を付けることができますが、何が起こっているのかを理解するためにはかなり多くのコードを含める必要がありますので、これが私の主な問題であると考えました。

+1

よく分かります – Flaom

+0

わからない場合は、マップを印刷して正しいかどうかを確認してみてください。あなたのコードはOKだと思います。なぜ出力が間違っているのかわからない場合は、別の質問を投稿し、コードのその部分を含めてください。 – ajb

答えて

3

あなたが単純化できてもはい、それは、正常に動作します:

int val = charCountAlpha.get(currentKey); 
val++; // add 1 to val 
charCountAlpha.put(currentKey, val); 

で:

charCountAlpha.put(currentKey, charCountAlpha.get(currentKey)+1); 

また、あなたが知られているキーセット(のようなを持っている場合TreeMapを使用する必要はおそらくありません代わりにHashMapを使用して、時間の複雑さを改善することができます。

関連する問題