In: Computer Science
Read the words in from the binary file and figure out how many times each word appears in the file. Display the results to the user.
Use ObjectInputStream to read binary file
Use a HashMap with the word as a key (String) and an Integer as the value. For each word, first check to see if it already exists in the Map. If not, add the word as key with a value of 1 for the Integer value. If it does, get the current value and increment by 1 – replace the old key,value with the new key, value. After all the words are processed and the HashMap is complete. Iterate through the Hash map and display the results in a user -friendly fashion.
Create an easy to read table and print to the console. Hint: Use tabs (/t) (values are not from file)
Example:
Word Count
A 190
Apple 6
Etc
SOLUTION:
Here is the code for the following problem.
I have also inserted comment at proper places so that you can easily understand the flow of code.
Please put your binary file in the same folder where you are storing your java file.
Also, if you have another name for the file, change the name in code also
----------------------------------------------------------------------------------------------------------------------------------
Binary File: input.dat:
This is the paragraph that I wrote to test the frequency of each
word in the file.
However you can make your own and test with this code.
Code:
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
// Creating a HashMap containing String as a key and occurrences as
a value
HashMap<String, Integer> charCountMap = new
HashMap<String, Integer>();
//read the binary file
try
{
File file = new File("input.dat");
Scanner scnr = new Scanner(file);
//read each word line by line and count the frequency
while(scnr.hasNext()){
//read next word
String word = scnr.next();
//count the frequency
if (charCountMap.containsKey(word)) {
// If word is present in charCountMap,
// incrementing it's count by 1
charCountMap.put(word, charCountMap.get(word)
+ 1);
}
else {
// If word is not present in charCountMap,
// putting this char to charCountMap with 1 as it's value
charCountMap.put(word, 1);
}
}
}
catch(Exception e)
{
//show an error message if unable to read the file
}
//display the frequency of each word
System.out.println("Word\t\tCount");
for (Map.Entry entry : charCountMap.entrySet()) {
System.out.printf("%-18s %d\n",
entry.getKey(),entry.getValue());
}
}
}
Output
Thank you,