/** * WordCounter: counts the number of a few words * * @author Clark F. Olson * @version 1.0 */ import java.util.Scanner; public class WordCounter { public static final int SIZE = 4; private String[] wordArray; private int[] occurrences; /** * WordCounter(): allocate and initialize the word array and the counter array * pre: SIZE > 0 * post: wordArray is initialized to the words of interest * and the counter array (occurrences) will be initialized to zeroes */ public WordCounter() { wordArray = new String[SIZE]; occurrences = new int[SIZE]; wordArray[0] = "the"; wordArray[1] = "not"; wordArray[2] = "memory"; wordArray[3] = "program"; for (int i = 0; i < SIZE; i++) { occurrences[i] = 0; } } /** * countOccurrences: Read all of the words in the wordFile and count the * number of occurrences of words in the wordArray * pre: wordArray and occurrences must be allocated and initialized * post: occurrences will hold the number of occurrences of the words in wordArray */ public void countOccurrences(Scanner wordFile) { while (wordFile.hasNext()) { String word = wordFile.next(); for (int i = 0; i < SIZE; i++) { if (wordArray[i].equals(word)) { occurrences[i]++; } } } } /** * displayTable: output the table of occurrences * pre: countOccurrences must have been called * post: the table is output to the console window */ public void displayTable() { for (int i = 0; i < SIZE; i++) { System.out.print(wordArray[i]); // Output sufficient spaces so that the occurrences are lined up correctly. for (int j = 0; j < 20 - wordArray[i].length(); j++) { System.out.print(" "); } System.out.println(occurrences[i]); } } }