Monday, 12 January 2015

// The "CountLetters" class.  (see page 243)
// (from Carter book)

import java.awt.*;
import hsa.Console;

public class CountLetters
{
    static Console c;           // The output console
   
    public static void main (String[] args)
    {
        c = new Console ();
        
        final int LOW = 'A';   // smallest possible value
        final int HIGH = 'Z';  // highest possible value
        int [] letterCounts = new int [HIGH - LOW + 1];
        // an array of counters
        String word;
        char [] wordLetters;       // an array of char (letters)
        int offset;
        
        // prompt user for a word
        c.print ("Enter a word: ");
        word = c.readLine();
        
        // convert the input word to a char array and count
        // letter occurrences
        word = word.toUpperCase();  // convert 'word' to uppercase
        wordLetters = word.toCharArray();  // convert 'word' to a char array
        for (int letter = 0; letter < wordLetters.length; letter++)
        {
            offset = wordLetters [letter] - LOW;
            letterCounts [offset] += 1;  // add 1 to appropriate counter
        } // end of for loopn # 1
        
        // show letter occurrences
        for (int i = LOW; i <= HIGH; i++)
        {
            c.println ((char) i + ": " + letterCounts [i - LOW]);
        } // end of for loop # 2
        
       
    } // end of main method
} // end of CountLetters class

No comments:

Post a Comment