The Artima Developer Community
Sponsored Link

Java Answers Forum
LetterCount

6 replies on 1 page. Most recent reply: Jan 13, 2003 6:35 PM by Matt Gerrans

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 6 replies on 1 page
JayN

Posts: 2
Nickname: jayn
Registered: Dec, 2002

LetterCount Posted: Dec 8, 2002 6:52 PM
Reply to this message Reply
Advertisement
I need to write a program that will read in a line of text, and output a list of all the letters that occur in the text along with the number of times each letters occurs.

Any suggestions?


Ugo Posada

Posts: 37
Nickname: binaryx
Registered: Dec, 2002

Re: LetterCount Posted: Jan 9, 2003 8:03 PM
Reply to this message Reply
Here you go, probably you already thought of a solution, if you did, I appreciate if you publish it here so I can compare it with mine.

//-------------------------------------------------------------------------
// Class name: LetterCount
// Purpose: Given an character input count the letters and print the results
// Author: Ugo Posada Zabala
// Date: 01/09/2003
//-------------------------------------------------------------------------
 
public class letterCount {
    
    private int[] alphabet;
    
    public letterCount() {
        alphabet = new int[26];        	
    }    
    
    public void addLetter(char l) {
    	
        //Make sure that the word is in lower case
        String c = Character.toString( Character.toLowerCase(l) );        
 
        //According to the letter insert it in its appropiate position in 
        //the alpphabet array
	    if ( c.equals("a") ) {
	        alphabet[0] = alphabet[0] + 1;	 	
	    } else if ( c.equals("b") ) {
	        alphabet[1] = alphabet[1] + 1;
        } else if ( c.equals("c") ) {
	        alphabet[2] = alphabet[2] + 1;
	    } else if ( c.equals("d") ) {
	        alphabet[3] = alphabet[3] + 1;    
        } else if ( c.equals("e") ) {
	        alphabet[4] = alphabet[4] + 1;
	    } else if ( c.equals("f") ) {
	        alphabet[5] = alphabet[5] + 1;
	    } else if ( c.equals("g") ) {
	        alphabet[6] = alphabet[6] + 1;  
	    } else if ( c.equals("h") ) {
	        alphabet[7] = alphabet[7] + 1;
	    } else if ( c.equals("i") ) {
	        alphabet[8] = alphabet[8] + 1;
	    } else if ( c.equals("j") ) {
	        alphabet[9] = alphabet[9] + 1;
	    } else if ( c.equals("k") ) {
	        alphabet[10] = alphabet[10] + 1;
	    } else if ( c.equals("l") ) {
	        alphabet[11] = alphabet[11] + 1; 
	    } else if ( c.equals("m") ) {
	        alphabet[12] = alphabet[12] + 1; 
	    } else if ( c.equals("n") ) {
	        alphabet[13] = alphabet[13] + 1;
	    } else if ( c.equals("o") ) {
	        alphabet[14] = alphabet[14] + 1;
	    } else if ( c.equals("p") ) {
	        alphabet[15] = alphabet[15] + 1;
	    } else if ( c.equals("q") ) {
	        alphabet[16] = alphabet[16] + 1;
	    } else if ( c.equals("r") ) {
	        alphabet[17] = alphabet[17] + 1; 
	    } else if ( c.equals("s") ) {
	        alphabet[18] = alphabet[18] + 1;
	    } else if ( c.equals("t") ) {
	        alphabet[19] = alphabet[19] + 1;     
	    } else if ( c.equals("u") ) {
	        alphabet[20] = alphabet[20] + 1;
	    } else if ( c.equals("v") ) {
	        alphabet[21] = alphabet[21] + 1; 
	    } else if ( c.equals("w") ) {
	        alphabet[22] = alphabet[22] + 1;
	    } else if ( c.equals("x") ) {
	        alphabet[23] = alphabet[23] + 1;
	    } else if ( c.equals("y") ) {
	        alphabet[24] = alphabet[24] + 1;
	    } else if ( c.equals("z") ) {
	        alphabet[25] = alphabet[25] + 1;                              
	    } else {
	    	System.err.println("Unrecognized character: " + c );                    
        }
    }
    
    public void printResults() {
       System.out.println("");
       System.out.println("--------------------------");
       System.out.println("----- Letter counter -----");
       System.out.println("--------------------------");
       System.out.println("");
       System.out.println("Number of a: "+alphabet[0]);	
       System.out.println("Number of b: "+alphabet[1]);
       System.out.println("Number of c: "+alphabet[2]);
       System.out.println("Number of d: "+alphabet[3]);
       System.out.println("Number of e: "+alphabet[4]);
       System.out.println("Number of f: "+alphabet[5]);	
       System.out.println("Number of g: "+alphabet[6]);
       System.out.println("Number of h: "+alphabet[7]);
       System.out.println("Number of i: "+alphabet[8]);
       System.out.println("Number of j: "+alphabet[9]);       
       System.out.println("Number of k: "+alphabet[10]);	
       System.out.println("Number of l: "+alphabet[11]);
       System.out.println("Number of m: "+alphabet[12]);
       System.out.println("Number of n: "+alphabet[13]);
       System.out.println("Number of o: "+alphabet[14]);
       System.out.println("Number of p: "+alphabet[15]);	
       System.out.println("Number of q: "+alphabet[16]);
       System.out.println("Number of r: "+alphabet[17]);
       System.out.println("Number of s: "+alphabet[18]);
       System.out.println("Number of t: "+alphabet[19]);       
       System.out.println("Number of u: "+alphabet[20]);	
       System.out.println("Number of v: "+alphabet[21]);
       System.out.println("Number of w: "+alphabet[22]);
       System.out.println("Number of x: "+alphabet[23]);
       System.out.println("Number of y: "+alphabet[24]);
       System.out.println("Number of z: "+alphabet[25]);
       System.out.println("");
       System.out.println("--------------------------");
       System.out.println("");	
    }	
        
    public static void main(String[] args){
        
        //If there is no input exit the program
        if (args.length == 0) {
        	System.out.println("No word to process");
        	return;
        }	
        
        //Paste all string input into one
        String letters = "";        
        for ( int i=0; i < args.length; i++) letters = letters + args[i];
        
        letterCount myLetterCount = new letterCount(); 
        
        //get each character from the input and process it
        for (int i=0; i < letters.length(); i++) {
            char letter = letters.charAt(i);
            myLetterCount.addLetter(letter);    	
        }
        
        //Print the count
        myLetterCount.printResults();	
    }	
}

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: LetterCount Posted: Jan 10, 2003 4:54 PM
Reply to this message Reply
Who said the letters were all English alphabet? What about upper case letters?

It would be much better and a lot less typing to use the facilities of the Java API, such as Character.isLetter(), Character.toLowerCase() or Character.toUpperCase() and collect the counts using a Map.

Ugo Posada

Posts: 37
Nickname: binaryx
Registered: Dec, 2002

Re: LetterCount Posted: Jan 11, 2003 6:33 PM
Reply to this message Reply
All letters are transformed to lower case, so that would not count. But I agree on the Map thing, your idea would be to add a new letter the first time it is found and if it was already stored just find it in the Map and sum 1 to the counter? Well thought.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: LetterCount Posted: Jan 13, 2003 4:12 PM
Reply to this message Reply
Here is an implementation using a Map. I wonder if C#'s boxing technique could make a similar C# implementation a little less cumbersome. Maybe I'll try that out...

import java.util.*;
 
class MutableInteger
{
   int value;
   public MutableInteger() {}
   public MutableInteger(int initialValue) { value = initialValue; }
   public int inc() { return ++value; }
   public int getValue() { return value; }
   public void setValue( int v ) { value  = v; }
   public String toString() { return new Integer(value).toString(); }
}
 
class LetterFrequencyThingy
{
   Map letterMap = new HashMap();
   String defaultKey = "non-letters";
   
   public LetterFrequencyThingy()
   {
      String letters = "abcdefghijklmnopqrstuvwxyz";
      for( int i = 0; i < letters.length(); i++ )
         letterMap.put( letters.substring(i,i+1), new MutableInteger() );
      letterMap.put( defaultKey, new MutableInteger() );
   }
   
   public Map update( String s )
   {
      s = s.toLowerCase();
 
      for( int i = 0; i < s.length(); i++ )
      {
         String letter = s.substring(i,i+1);
 
         if( letterMap.containsKey(letter) )
            ((MutableInteger)letterMap.get(letter)).inc();
         else
            ((MutableInteger)letterMap.get(defaultKey)).inc();
      }
      return letterMap;
   }
   
   public static void main(String args[])
   {
      LetterFrequencyThingy thingy = new LetterFrequencyThingy();
      Map letterMap = thingy.update( "Let's just see how well this thing works, okay?" );
 
      Set keys = letterMap.keySet();
      Iterator i = keys.iterator();
      while( i.hasNext() )
      {
         Object key = i.next();
         System.out.println( key + " - " + letterMap.get(key) );
      }
   }
}

Ugo Posada

Posts: 37
Nickname: binaryx
Registered: Dec, 2002

Re: LetterCount Posted: Jan 13, 2003 5:45 PM
Reply to this message Reply
Very elegant solution, I liked it, however, I got a question:

How do I know which type of collection should I use. I always try to fit every problem's solution to a vector but I know is not a good approach. Do you have a good tutorial to recommend?

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: LetterCount Posted: Jan 13, 2003 6:35 PM
Reply to this message Reply
That is a good question. After years of programming, the choice seems "natural," but of course, it really isn't. There is a tutorial on collections at Sun's site: http://developer.java.sun.com/developer/onlineTraining/collections/, but it looks a bit heavy and theoretical (and pretty long). I don't know of a practical tutorial that outlines how to choose a collection type for particular tasks, but I think that would be a good article. Maybe someone else on the list has seen such an article on JavaWorld, or elsewhere.

Generally when you have a set of unique keys that each have an associated value (as in this case), you are looking at a Map. Lists (Vector is a List, by the way) are more common when you have a simple collection of values where there may be duplicates and order is maintained. A List often just functions as a more flexible array, since it grows and shrinks dynamically. Sets are used when you have a set of values, each of which is unique and usually the order is unimportant. There are also different implementations of these interfaces; choosing these is usually dependent on what you are doing with the data and whether performance or memory constraints are more important. For instance, you'd probably want to implement a queue with a LinkedList instead of an ArrayList, because adding and removing items from either end of a LinkedList is of equivalent (and fairly reasonable) speed, whereas adding to and removing from the beginning of an ArrayList is costly.

Flat View: This topic has 6 replies on 1 page
Topic: What is System? Previous Topic   Next Topic Topic: using api in java

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use