Avatar of Atouray

asked on 

Using hashtables to count the number of occurence of a word

I am using hashtable to count the word frequency of any all the words in my text file. eg if the word "good" appears 10 times in my text file it should print "good 10" my code can only read the first line of the text file and cannot cannot continue further, i have been trying to figure it out but its still a problem. I have attached the code so far.
import java.io.*;
import java.util.*;
public class WordFrequency {
	public static void main(String[] args) throws IOException {
		WordFrequency test = new WordFrequency();
	public void countWordFre() throws IOException {
		Scanner in = new Scanner(new FileInputStream("in.txt"));
		PrintWriter out = new PrintWriter(new FileOutputStream("out.txt"));
		Hashtable map = new Hashtable();
		String line = in.nextLine();
		String word;
		StringTokenizer st = new StringTokenizer(line);
		while (st.hasMoreTokens()) {
			word = st.nextToken().toLowerCase();
			if (map.containsKey(word)) {
				int count = (Integer) map.get(word);
				map.put(word, count + 1);
			} else {
				map.put(word, 1);
		Enumeration<String> e = map.keys();
		while (e.hasMoreElements()) {
			 word =e.nextElement();
			out.println(word + " " + map.get(word));

Open in new window

Web ServersJavaJava App Servers

Avatar of undefined
Last Comment

8/22/2022 - Mon