Source of FrequencyCounter.java


  1: import java.util.Iterator;
  2: import java.util.Scanner;
  3: /**
  4:    A class that counts the number of times each word occurs in a document.
  5:    
  6:    @author Frank M. Carrano
  7:    @author Timothy M. Henry
  8:    @version 4.0
  9: */
 10: public class FrequencyCounter
 11: {
 12:    private DictionaryInterface<String, Integer> wordTable;
 13: 
 14:    public FrequencyCounter() 
 15:    {
 16:       wordTable = new SortedDictionary<>();
 17:    } // end default constructor
 18:    
 19:    // 19.16
 20:    /** Reads a text file of words and counts their frequencies of occurrence.
 21:        @param data  A text scanner for the text file of data. */
 22:    public void readFile(Scanner data)
 23:    {
 24:       data.useDelimiter("\\W+");
 25: 
 26:       while (data.hasNext())
 27:       {
 28:          String nextWord = data.next();
 29:          nextWord = nextWord.toLowerCase();
 30:          Integer frequency = wordTable.getValue(nextWord);
 31: 
 32:          if (frequency == null)
 33:          { // Add new word to table
 34:             wordTable.add(nextWord, new Integer(1));
 35:          }
 36:          else
 37:          {  // Increment count of existing word; replace wordTable entry
 38:             frequency++;
 39:             wordTable.add(nextWord, frequency);
 40:          } // end if
 41:       } // end while
 42: 
 43:       data.close();
 44:    } // end readFile
 45:    // 19.17
 46:    /** Displays words and their frequencies of occurrence. */
 47:    public void display()
 48:    {
 49:       Iterator<String>  keyIterator   = wordTable.getKeyIterator();
 50:       Iterator<Integer> valueIterator = wordTable.getValueIterator();
 51: 
 52:       while (keyIterator.hasNext())
 53:       {
 54:          System.out.println(keyIterator.next() + " " + valueIterator.next());
 55:       } // end while    
 56:    } // end display
 57: } // end FrequencyCounter