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!

Recommended Answers

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.

Jump to Post

malli: something that just came to me now (didn't notice it in your previous source codes).
besides the fact that your code is faultive as can be (according to your code: é is a digit, which it really isn't.)
if you want to boost up the efficiency of that code …

Jump to Post

All 6 Replies

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();
        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
package arrayexample1;
import java.util.Scanner;
public class CountingLettersFromString 
{
    public static void main(String[]args)
    {
        char s2;
        Scanner sc=new Scanner(System.in);
        System.out.println("enter a string ....");
        int count=0;
        String s1=sc.nextLine();
        int l=s1.length();
        for(int i=0;i<l;i++)
        {
          s2=s1.charAt(i);

           if(s2==' '|s2=='A'|s2=='a'|s2=='B'|s2=='b'|s2=='C'|s2=='c'|s2=='D'|s2=='d'|s2=='E'|s2=='e'|s2=='F'|s2=='f'|s2=='G'|s2=='g'|s2=='H'|s2=='h'|s2=='I'|s2=='i'|s2=='J'|s2=='j'|s2=='K'|s2=='k'|s2=='L'|s2=='l'|s2=='M'|s2=='m'|s2=='N'|s2=='n'|s2=='O'|s2=='o'|s2=='P'|s2=='p'|s2=='Q'|s2=='q'|s2=='R'|s2=='r'|s2=='S'|s2=='s'|s2=='T'|s2=='t'|s2=='U'|s2=='u'|s2=='V'|s2=='v'|s2=='W'|s2=='w'|s2=='X'|s2=='x'|s2=='y'|s2=='y'|s2=='Z'|s2=='z')

          count++;



           else if(s2=='@'|s2=='#'|s2=='$'|s2=='&'|s2=='!'|s2=='%'|s2==','|s2==':'|s2=='<'|s2=='>'|s2=='?'|s2=='^'|s2=='('|s2==')'|s2=='+'|s2=='-'|s2=='*'|s2=='{'|s2=='}'|s2=='['|s2==']')
           {
                  System.out.println(s2+"special symbols...");
           }  
              else


                               System.out.println(s2+"is a digit");


          }
        System.out.println("total no of letters in a string is " +count++);
    }

    }            

malli: something that just came to me now (didn't notice it in your previous source codes).
besides the fact that your code is faultive as can be (according to your code: é is a digit, which it really isn't.)
if you want to boost up the efficiency of that code (granted, in a small snippet like this, the difference will be minimal, but still.... )

you may want to go over the basics of Java, and check the difference between the | operator and the || operator.

also: please stop reviving dead threads, by just posting code that should (at the very least) be refactored.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.