Please write the code for this class in JAVA and implementin

Please write the code for this class in JAVA and implementing the required things :

Open a text file containing a variable number of words. Create an instance of your Hashtable class. Read in words from the text file until the end of the file is reached Look up the word in your hash table. If word is found Increment its count in the hash table otherwise Add the word to the hash table and set its count to 1. Print out the words and their counts

Solution

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;

public class WordCount {
   static final Integer ONE = new Integer(1);

   /**
   * @param args
   * @throws IOException
   */
   public static void main(String args[]) throws IOException {
       Hashtable<String, Integer> map = new Hashtable<String, Integer>();
       FileReader fr = new FileReader(\"words.txt\");
       BufferedReader br = new BufferedReader(fr);
       String line;
       while ((line = br.readLine()) != null) {
           processLine(line, map);
       }
       br.close();
       Enumeration<String> e = map.keys();
       while (e.hasMoreElements()) {
           String key = (String) e.nextElement();
           System.out.println(key + \" : \" + map.get(key));
       }

   }

   /**
   * method to process the line
   *
   * @param line
   * @param map
   */
   private static void processLine(String line, Hashtable<String, Integer> map) {
       StringTokenizer st = new StringTokenizer(line);
       while (st.hasMoreTokens()) {
           addWord(map, st.nextToken());
       }
   }

   /**
   * method to add and count the words in the map
   *
   * @param map
   * @param word
   */
   private static void addWord(Hashtable<String, Integer> map, String word) {
       Object obj = map.get(word);
       if (obj == null) {
           map.put(word, ONE);
       } else {
           int i = ((Integer) obj).intValue() + 1;
           map.put(word, new Integer(i));
       }
   }
}

words.txt

beef and pork next yeer, the government said Wednesdaay, as consumers bear some of the bruntt of the sweltering heat that is drivng up the cost of feed corrn.

OUTPUT:

bear : 1
corrn. : 1
is : 1
feed : 1
that : 1
said : 1
the : 4
up : 1
yeer, : 1
some : 1
as : 1
bruntt : 1
of : 3
pork : 1
next : 1
sweltering : 1
beef : 1
drivng : 1
consumers : 1
cost : 1
government : 1
Wednesdaay, : 1
heat : 1
and : 1

Please write the code for this class in JAVA and implementing the required things : Open a text file containing a variable number of words. Create an instance o
Please write the code for this class in JAVA and implementing the required things : Open a text file containing a variable number of words. Create an instance o

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site