Question: Please write a program that meets the following requirements: 1. Create a Word class that contains two instance variables, a String for the word and

Please write a program that meets the following requirements:

1. Create a Word class that contains two instance variables, a String for the word and an int representing its frequency.

2. Word must contain a constructor that accepts one parameter, a String (which is the word). The constructor should set the frequency to one.

3. Make the String in Word final. Its value will be assigned in the constructor and never changed. Provide an accessor for the String. Provide an accessor for the frequency. Also implement a method that increments the frequency by 1.

4. Word should have a toString method that returns the word and its frequency. 5. Word should also implement the Comparable interface. By

implementing the interface, Word must contain a method called compareTo which accepts another Word as the parameter and returns an int. When comparing Words, the word with the higher frequency should come first.

6. Create a WordCounter class with an List of Word as an instance variable. Initialize this with an ArrayList.

7. WordCounter should contain a method called parseBook which accepts a String as a parameter which represents the name of the file to open. The parseBook method will open the file using a Scanner, and use a while loop to acquire each word. Your program should check if the word is already in the list. If it is, its frequency should be incremented. If the word is not in the word list, then it should be added. When parseBook finishes, it should return the total number of unique Words stored in the list.

8. WordCounter should have a method called printTopWords which accepts an int n and then prints the n most frequent words in order (most frequent ones first). Make sure you sort the List first. Note that calling the List sort method with a null parameter will sort the list according to Word's compareTo method.

9. You will need a main method to drive the program. Put it at the bottom of the WordCounter class (inside the class, but after all the other methods). Inside the main method, instantiate a WordCounter. Invoke the Word Counter objects parseBook method passing it the name of a file, and then print the result (which will be the number of words in the text). Finally, print out the top 10 most frequent words.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!