Static method to count occurrences of a letter in a lower case word using maps

Tags: , , ,



I have to create a class called MakeMap with a single static method called countLetters(). The method should take as a parameter a word formed of lowercase letters and return a map of the counts of the letters in the word. This is the test code for the Main class (which I cannot edit):

import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Main
{
   public static void main(String [] args)
   {
      Map<Character, Integer> count = MakeMap.countLetters("hello");
      List<Character> letters = new ArrayList<Character>(count.keySet());
      Collections.sort(letters);
      for(Character letter : letters)
         System.out.println("There are " + count.get(letter) + " of the letter '" + letter + "'");
   }
}

The output must be formatted like this also: $ java Main There are 1 of the letter ‘e’ There are 1 of the letter ‘h’ There are 2 of the letter ‘l’ There are 1 of the letter ‘o’

This is what I have attempted so far in my MakeMap class. I feel like I only need a couple of minor adjustments to get this working.

import java.util.Map;
import java.util.TreeMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class MakeMap
{
    public static Map countLetters(String word)
    {
        HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
        String w = word.toLowerCase();
  
        // checking each char of strArray 
        for(int i = 0; i < word.length(); i++)
        {
            if(charCountMap.containsKey(word.charAt(i)))
            { 
                // If char is present in charCountMap, 
                // incrementing it's count by 1 
                charCountMap.put(word.charAt(i), charCountMap.get((word.charAt(i)) + 1 ));
            } 
            else
            { 
                // If char is not present in charCountMap, 
                // putting this char to charCountMap with 1 as it's value 
                charCountMap.put(word.charAt(i), 1); 
            }
        }
        return charCountMap;
    }

}

This is the error message I am getting: Note: Main.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.

Answer

Incorrect brackets, should be:

charCountMap.put(word.charAt(i), (charCountMap.get(word.charAt(i)) + 1));

additionaly you must return charCountMap from this method isntead of print it out there, so the method must be defined as public static Map<Character, Integer> countLetters(String word)



Source: stackoverflow