Java: WordCount mit Hashtable

Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen

  • Java: WordCount mit Hashtable

    Quellcode

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



    "wordcount.dat" schrieb:

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



    Ausgabe:
    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