1.11M Members

Counting Letters in a String



I am taking my first Java class this semester, and I have run into an assignment that just has me stumped:

I am to write a program that will count the number of occurrences of each letter in a string the user inputs. It is in a section discussing Maps, HashMaps, StringTokenizers, and TreeSets, so I am assuming that I need to use these if possible.

Here is what I have so far:

/** Program that counts the number of occurrences of each letter.
   * LetterTypeCount.java

import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.Scanner;

public class LetterTypeCount
   private Map< String, Integer > map;
   private Scanner scanner;

   public LetterTypeCount()
      map = new HashMap< String, Integer >(); // create HashMap
      scanner = new Scanner( System.in ); // create scanner
      createMap(); // create map based on user input
      displayMap(); // display map content
   } // end LetterTypeCount constructor

   // create map from user input
   private void createMap()
      System.out.println( "Enter a string:" ); // prompt for user input
      String input = scanner.nextLine();

      // create StringTokenizer for input
      StringTokenizer str = new StringTokenizer( input );
      // process input text
      while ( str.hasMoreTokens() ) // while more input
         String symbol = str.nextToken().toLowerCase(); // get letter

         // if the map contains the word
         if ( map.containsKey( symbol ) ) // is letter in map
            int count = map.get( symbol ); // get current count
            map.put( symbol, count + 1 ); // increment count
         } // end if
            map.put( symbol, 1 ); // add new letter with a count of 1 to map
      } // end while
   } // end method createMap

   // display map content
   private void displayMap()
      Set< String > keys = map.keySet(); // get keys

      // sort keys
      TreeSet< String > sortedKeys = new TreeSet< String >( keys );

      System.out.println( "Map contains:\nKey\t\tValue" );

      // generate output for each key in map
      for ( String key : sortedKeys )
         System.out.printf( "%-10s%10s\n", key, map.get( key ) );

         "\nsize:%d\nisEmpty:%b\n", map.size(), map.isEmpty() );
   } // end method displayMap

   public static void main( String args[] )
      new LetterTypeCount();
   } // end main
} // end class LetterTypeCount

It is almost working...my output counts the words in the string:

Enter a string:
Here is a string
Map contains:
Key		Value
a                  1
here               1
is                 1
string             1

BUILD SUCCESSFUL (total time: 5 seconds)

I would like my output to list each letter on the left with the number of occurrences on the right. I am probably making an obvious mistake, but after looking at this all week, I've got nothing left.

Any advice?

Since this is my first forum and first post, I hope I am following all of the appropriate guidelines. If not, please let me know.

Thank you!


While combing through tutorials, I was focusing on the StringTokenizer. After working on this for so long, I decided to start from scratch and reviewed HashMaps.

Obviously, my keys are completely wrong, so I am updating those now.


Why don't you try the API for String, and the methods indexOf. If it returns something not -1 then increase a count++ and search for the occurrence of the letter after that index.


Thank you.

I'll give that a try.


try This and good lack:

 public static void main(String[] args) {
        String returnedString="";
       StringBuffer st= new StringBuffer("aannjn");
        int pos=0;
        int times=0;
         String str=st.toString();
            char ch=st.charAt(0);
            int max=str.length();    
            while((pos=str.indexOf(ch))!=-1 ){

       returnedString+=ch +":"+ times+"\n";


// imputs:
This article has been dead for over six months: Start a new discussion instead
Start New Discussion
Tags Related to this Article