JAVA Letter Frequency

Posted by Tully on Mon 21 June 2010

I picked up a book on JAVA this last weekend at the local borders. The book I bought was JAVA in 24 hours. So far I'm on page 116 in 2 days and the read is very easy. I'm currently on chapter 9 "Storing Information with Arrays" and found JAVA a very easy language to pick up. In this chapter they have an example program that counts the letter frequency in an array of phrases. I thought this was pretty cool and have provided the JAVA class below.

I plan on developing Android applications within the next couple months. I set-up the Android SDK and emulator with Net Beans IDE. So far I have only created the basic "Hello World!" application which I got running successfully.

Word Frequency Class

class Wheel {
    public static void main(String[] args) {
        String phrase[] = {"A STITCH IN TIME SAVES NINE",
                           "DON'T EAT YELLOW SNOW",
                           "JUST DO IT",
                           "EVERY GOOD BOY DOES FINE",
                           "I WANT MY MTV", "I LIKE IKE",
                           "PLAY IT AGAIN, SAME",
                           "FROSTY THE SNOWMAN",
                           "ONE MORE FOR THE ROAD",
                           "HOME FIELD ADVANTAGE",
                           "VALENTINE'S DAY MASSACRE",
                           "GROVER CLEVELAN OHIO",
                           "SPAGHETTI WESTERN",
                           "AQUA TEEN HUNGER FORCE",
                           "IT'S A WONDERFUL LIFE"};
        int[] letterCount = new int[26];

        for (int count = 0; count < phrase.length; count++) {
            String current = phrase[count];
            char[] letters = current.toCharArray();

            for (int count2 = 0; count2 < letters.length; count2++) {
                char lett = letters[count2];

                if ( (lett >= 'A') & (lett <= 'Z') ) {
                    letterCount[lett - 'A']++;
                }
            }
        }

        for (char count = 'A'; count <= 'Z'; count++) {
            System.out.print(count + ": " + letterCount[count - 'A'] + " ");
        }

        System.out.println();
    }
}

Output

A: 22 B: 1 C: 4 D: 9 E: 34 F: 7 G: 6 H: 7 I: 18 J: 1 K: 2 L: 10 M: 8 N:19
O: 20 P: 2 Q: 1 R: 12 S: 15 T: 20 U: 4 V: 7 W: 6 X: 0 Y: 7 Z: 0