1,105,399 Community Members

Counting Letters in a String

Member Avatar
hbelle.28
Newbie Poster
3 posts since Apr 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi,

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
         else
            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 ) );

      System.out.printf(
         "\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

size:4
isEmpty:false
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?

P.S.
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!

Member Avatar
hbelle.28
Newbie Poster
3 posts since Apr 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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.

Member Avatar
javaAddict
Nearly a Senior Poster
3,274 posts since Dec 2007
Reputation Points: 900 [?]
Q&As Helped to Solve: 448 [?]
Skill Endorsements: 8 [?]
Team Colleague
Featured
 
0
 

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.

Member Avatar
hbelle.28
Newbie Poster
3 posts since Apr 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thank you.

I'll give that a try.

Member Avatar
Bernard LeRoi
Newbie Poster
1 post since Sep 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-1
 

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();
        while(st.length()>0){
            char ch=st.charAt(0);
            times=0;    
            int max=str.length();    
            while((pos=str.indexOf(ch))!=-1 ){
              times++;          
             st.deleteCharAt(pos);
             str=st.toString();
         }

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

         System.out.println(returnedString);// 
    }


}
// imputs:
   a:2
   n:3
   j:1
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article