The first step will be to continually ask the user to enter

The first step will be to continually ask the user to enter text until they enter the string \"Done\" to signal they are finished. Every time the user types a sentence, we will need to break the sentence into each of its individual words. We\'ll then need to do two things with these words: 1. Keep a list of all the individual words the user has entered 2. Keep a count of how many times the user entered that particular word Hmm, this sounds like a perfect job for a couple of vectors! When the user signals they are finished entering text (by typing \"Done\"), we will then sort all of the words the user entered into alphabetical order. Once the words have been alphabetized, we\'ll print the words in alphabetical order along with a series of x\'s denoting each time the word was entered. See the following sample output:

Solution

WordsTracker.java

import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeMap;


public class WordsTracker {

  
   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       TreeMap<String, Integer> map = new TreeMap<String , Integer>(new MyComparator());
       String s = \"\";
       while(!s.equalsIgnoreCase(\"Done\")){
       System.out.println(\"Enter a sentence or \\\"Done\\\" to finish: \");
       s = scan.nextLine();
       if(!s.equalsIgnoreCase(\"Done\")){
       String words[] = s.split(\"\\\\s+\");
       for(String word: words){
           if(map.containsKey(word)){
               map.put(word, map.get(word)+1);
           }
           else{
               map.put(word, 1);
           }
       }
       }
       }
      
       for(String key: map.keySet()){
           System.out.print(key+\": \");
           for(int i=0; i<map.get(key);i++){
               System.out.print(\"X\");
           }
           System.out.println();
       }

   }

}
class MyComparator implements Comparator<String>
{
public int compare(String o1,String o2)
{
return o1.compareTo(o2);
}
}

Output:

Enter a sentence or \"Done\" to finish:
I would like to have the dog
Enter a sentence or \"Done\" to finish:
The quick brown fox jumped over the lazy dog
Enter a sentence or \"Done\" to finish:
Done
I: X
The: X
brown: X
dog: XX
fox: X
have: X
jumped: X
lazy: X
like: X
over: X
quick: X
the: XX
to: X
would: X

 The first step will be to continually ask the user to enter text until they enter the string \
 The first step will be to continually ask the user to enter text until they enter the string \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site