Question
[JAVA] ( Count the occurrences of words in a text file ) Rewrite Listing 21.9 to read the text from a text file. The text
[JAVA]
(Count the occurrences of words in a text file) Rewrite Listing 21.9 to read the text from a text file. The text file is passed as a command-line argument. Words are delimited by whitespace characters, punctuation marks (, ; . : ?), quotation marks (' "), and parentheses. Count the words in a case-sensitive fashion (e.g., consider Good and good to be the same word). The words must start with a letter. Display the output of words in alphabetical order, with each word preceded by the number of times it occurs.
I want to be able to enter a file name manully when running the program(NO CMD) and it should work correctly. Must use set/maps not simple code or different code.
import java.util.*; import java.io.*;
public class WordCounter {
public static void main(String[] args){
//String fileName = args[0];
TreeMap
int wordCount = 0;
try{
Scanner input = new Scanner(new File(fileName));
while (input.hasNextLine()){
String line=input.nextLine();
String[]words=line.split("[\\s+\\p{P}]");
wordCount = wordCount+words.length;
for (int i=0;i if (words[i].trim().length () >0 && words[i].trim().matches("[A-Z|a-z]+")){ String key =words[i].toLowerCase(); if (treeMap.get(key)!=null){ int count =treeMap.get(key); count++; treeMap.put(key,count); } else{ treeMap.put(key, 1); } } } } } catch (Exception ex){ ex.printStackTrace(); } Set System.out.println(" Total words: "+wordCount); for (Map.Entry System.out.println(entry.getValue()+"\t" +entry.getKey()); } } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access with AI-Powered Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started