The first step will be to continually ask the user to enter
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

