You are not logged in.

  • Login

1

Thursday, March 23rd 2006, 5:09pm

Java: WordCount mit Hashtable

Java Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.io.File;
import java.io.IOException;
import java.util.*;
public class A3_WordCount_Vektor {
 
	static Hashtable words = new Hashtable();
	public static void main(String[] args) throws IOException
	{
		Scanner In = new Scanner(new File("wordcount.dat"));
		while(In.hasNext()) {
			String word = In.next();
			countWord(word);
		}
		In.close();
		//printTable();
	}
 
	static void countWord(String word) {
		if (findWord(word) == null) // Wenn das Wort noch nicht existiert, nehme es in die Hashtable auf
			enterWord(word);
		else // existiert das Wort schon in der Datenbank, dann erhöhe seinen Zähler
			incNumOfWord(word);
	}
 
	/**
	 * Gibt den Wert des Wortes zurück bzw. null, falls das Wort noch nicht existiert
	 * @param word
	 * @return
	 */
	static Object findWord(String word) {
		return words.get(word);
	}
 
	/**
	 * Fügt das Wort in die Hashtable hinzu
	 * @param word
	 */
	static void enterWord(String word) {
		Integer Onumber = new Integer(1);
		words.put(word, Onumber);
	}
 
 
	/**
	 * Erhöht den Zähler des Wortes
	 * @param word
	 */
	static void incNumOfWord(String word) {
		int number = ((Integer)words.get(word)).intValue();
		Integer Onumber = new Integer(number+1);
		words.put(word,Onumber);
	}
 
	/**
	 * gibt die fertige Hashtable aus
	 *
	 */
	static void printTable() {
		Enumeration e = words.keys();
		while(e.hasMoreElements()) {
			String word = (String) e.nextElement();
			System.out.println(word + ":\t" + words.get(word) + "mal");
		}
	}
 
}



Quoted from ""wordcount.dat""

easy coding und coder wiki wünschen viel erfolgt in der easy klausur let's wiki



Ausgabe:

Quoted

wünschen: 1mal
coder: 1mal
viel: 1mal
easy: 2mal
klausur: 1mal
erfolgt: 1mal
der: 1mal
in: 1mal
coding: 1mal
und: 1mal
let's: 1mal
wiki: 2mal

Similar threads

Social bookmarks