Java TreeMaps 1). Use a Java TreeMap 2). Count the number of times each word in
ID: 3682377 • Letter: J
Question
Java TreeMaps1). Use a Java TreeMap 2). Count the number of times each word in a sentence or paragraph (case-sensitive) shows up from System.in. 3). If a blank line is entered, use System.exit(0); 4). Print each word on a separate line, along with its count, in case-sensitive lexicographical order. 5). You must do this entirely in a single main method.
The output should look something like this:
art is a fancy thing that a cat likes to eat cheese thing banana art art art I LIKE LIKE: 1 a: art 4 banana: 1 cat1 cheese: 1 eat 1 fancy: 1 is 1 likes 1 that: 1 thing: 2 to: 1
Explanation / Answer
/**The java program TreeMapTester that prompts user to enter the line of text and then press ente key. Then the program finds the count of occurrences of each word.*/
//TreeMapTester.java
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class TreeMapTester {
public static void main(String[] args) {
//Create a Scanner class object
Scanner scanner=new Scanner(System.in);
//Create TreeMap object of String key and integer value
TreeMap<String, Integer>treemap=new TreeMap<>();
System.out.println("Enter a input of text : ");
//read a line of text
String text=scanner.nextLine();
//Check if the text input is empty
if(text.isEmpty())
{
System.out.println("Program closed");
//terminate the program
System.exit(0);
}
else
{
//Create a list of array strings from text line input
String[] words=text.trim().split(" ");
//Run for each loop on words array
for (String word : words)
{
//Check if treemap contains word
if (treemap.containsKey(word))
{
//Increment the count of the word by one
//at key location word.
treemap.put(word, treemap.get(word) + 1);
}
else
{
//Otherwise put the word and set value 1
treemap.put(word, 1);
}
}
}
//Print the key and count of each word to console
//Create an entry set on treemap and call getKey and getValue
for (Map.Entry<String, Integer> entry : treemap.entrySet())
{
System.out.println(entry.getKey() +" : "+entry.getValue());
}
}
}//end of the class
--------------------------------------------------------------------------------------------------------------------------------
Sample Output:
Enter a input of text :
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
fancy : 1
is : 1
likes : 1
that : 1
thing : 2
to : 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.