This class should be called Program2 and not be in a package. Using a TreeMap, c
ID: 3604905 • Letter: T
Question
This class should be called Program2 and not be in a package. Using a TreeMap, count the number of times that each word (case-sensitive) shows up in System.in. End your program when a blank line is entered. Print out each word, and its count, in case-sensitive lexicographical order (the default for String values). Finally, print out the most frequently used word in the input. This can, and should, be done entirely in a single main method. Here’s a sample run from my program:
art is a fancy thing that a cat likes to eat cheese thing banana art art art I LIKE
I: 1 LIKE : 1 a: 2 art : 4 banana : 1 cat : 1 cheese : 1 eat : 1 2 fancy : 1 is : 1 likes : 1 that : 1 thing : 2 to : 1 Most common word : art
Explanation / Answer
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Program2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
TreeMap<String, Integer> map = new TreeMap<>();
System.out.println("Enter words(space to stop: ");
String line;
while(true) {
line = sc.nextLine().trim();
if(line.isEmpty())
break;
if(map.containsKey(line)) {
map.put(line, map.get(line)+1);
}else
map.put(line, 1);
}
sc.close();
//System.out.println(map);
String max = "";
int maxCount = 0;
for(Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
if(entry.getValue() > maxCount) {
maxCount = entry.getValue();
max = entry.getKey();
}
}
System.out.println("Most common word : "+max);
}
}
/*
Sample run:
Enter words(space to stop:
this
is
a
boy
that
can
be
can
is
a
a:2
be:1
boy:1
can:2
is:2
that:1
this:1
Most common word : a
*/