Question: Rewrite Listing 21.9 to read the text from a text file. The text file is passed as a command-line argument. Words are delimited by whitespace

Rewrite Listing 21.9 to read the text from a text file. The text file is passed as a command-line argument. Words are delimited by whitespace characters, punctuation marks (,;.:?), quotation marks ('"), and parentheses. Count words in case-insensitive fashion (e.g., consider Good and good to be the same word). The words must start with a letter. Display the output in alphabetical order of words, with each word preceded by its occurrence count.

Listing

1 import java.util.*; 2 3 public class CountOccurrence0fWords { 4 public static

void main(String[] args) { // Set text in a string String text

1 import java.util.*; 2 3 public class CountOccurrence0fWords { 4 public static void main(String[] args) { // Set text in a string String text = "Good morning. Have a good class. " + "Have a good visit. Have fun!"; 5 // Create a TreeMap to hold words as key and count as value Map map = new TreeMap (); 10 11 12 13 String[] words = text.split("[ \t .,;:!?(){}]"); for (int i = 0; i < words.length; i++) { String key = words[i].toLowerCase(); 14 |15 if (key.length() > 0) { if (!map.containskey(key)) { map.put(key, 1); 16 |17 18 19 20 21 22 23 24 25 26 27 28 29 30 else { int value = map.get(key); value++; map.put(key, value); // Get all entries into a set Set entrySet = map.entrySet(); // Get key and value from each entry for (Map.Entry entry: entrySet) System.out.println(entry.getKey() + "\t" + entry.getValue()); 31 32 33 34 35 } a 2 class fun good have 3 morning visit

Step by Step Solution

3.54 Rating (157 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

Program Plan Step 1 Reads the text from the text file ... View full answer

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 Java Programming Questions!