C:\Users\notebook\Documents\NetBeansProjects\CS2\src\applications\FrequencyCounter.java
 1 /*
 2  * Program which:
 3  * - Prompts the user for a file name
 4  * - Reads the specified file, which is presumed to contain punctuation 
 5  *   free lyrics to a song
 6  * - Computes the frequency of occurence of each word in a file
 7  * - Displays the resulting words, along with their frequency of occurence,
 8  *   in alphbetical order, to the output stream
 9  * - Makes use of the BinaryTree class created for the last assignment
10  */
11 package applications;
12 
13 import java.io.File;
14 import java.io.FileNotFoundException;
15 import java.util.Scanner;
16 import trees.BinaryTree;
17 import trees.BinaryTreeCreationException;
18 
19 /**
20  *
21  * @author notebook
22  */
23 public class FrequencyCounter {
24 
25     /**
26      * @param args the command line arguments
27      */
28     public static void main(String[] args) throws FileNotFoundException, BinaryTreeCreationException {
29         Scanner scanner = equateScannerWithFile();
30         BinaryTree<String, Integer> counter = frequencyCounter(scanner);
31         display(counter);
32     }
33 
34     private static Scanner equateScannerWithFile() throws FileNotFoundException {
35         System.out.print("Enter file name here: ");
36         Scanner s = new Scanner(System.in);
37         String fileName = s.nextLine();
38         String FullFileName = createFullFileName(fileName);
39         return new Scanner(new File(FullFileName));
40     }
41 
42     private static BinaryTree<String, Integer> frequencyCounter(Scanner scanner) throws BinaryTreeCreationException {
43         BinaryTree<String, Integer> tree = new BinaryTree<>();
44         while (scanner.hasNext()) {
45             String key = scanner.next().toLowerCase();
46             if (tree.member(key)) {
47                 tree.find(key).setValue(tree.get(key) + 1);
48             } else {
49                 tree.addST(key, 1);
50             }
51         }
52         return tree;
53     }
54 
55     private static void display(BinaryTree<String, Integer> counter) {
56         counter.inorder();
57     }
58 
59     private static String createFullFileName(String fileName) {
60         String separator = System.getProperty("file.separator");
61         String home = System.getProperty("user.home");
62         String path = home + separator + "Documents" + separator + "NetBeansProjects" + separator;
63         String fullFileName = path + fileName;
64         return fullFileName;
65     }
66 
67 }
68