diff options
Diffstat (limited to 'src/de/fhswf/in/inf/java1/aufgabe9/WordCount.java')
| -rw-r--r-- | src/de/fhswf/in/inf/java1/aufgabe9/WordCount.java | 61 |
1 files changed, 56 insertions, 5 deletions
diff --git a/src/de/fhswf/in/inf/java1/aufgabe9/WordCount.java b/src/de/fhswf/in/inf/java1/aufgabe9/WordCount.java index fcd5373..a6d90ef 100644 --- a/src/de/fhswf/in/inf/java1/aufgabe9/WordCount.java +++ b/src/de/fhswf/in/inf/java1/aufgabe9/WordCount.java @@ -7,7 +7,9 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; +import java.util.Collections; import java.util.Map.Entry; +import java.util.Set; import java.util.TreeMap; /** @@ -22,15 +24,26 @@ public class WordCount private TreeMap<String, Integer> wordMap = new TreeMap<>(); /** - * Reads the file and counts the words. + * Empty constructor. + * + */ + public WordCount() + { + + } + + /** + * Reads a file and counts the words. * * @param file - * The file to be counted. + * The file to be read. */ - public WordCount(File file) + public final void readFile(File file) { try (BufferedReader f = new BufferedReader(new FileReader(file))) { + wordMap.clear(); + String line = null; while ((line = f.readLine()) != null) @@ -44,9 +57,10 @@ public class WordCount { word = word.toLowerCase(); - if (wordMap.containsKey(word)) + Integer tmp = wordMap.get(word); + if (tmp != null) { - wordMap.put(word, wordMap.get(word) + 1); + wordMap.put(word, tmp + 1); } else { @@ -79,4 +93,41 @@ public class WordCount return ret.toString(); } + + /** + * Returns all words from the file. + * + * @return An unmodifiable Set of the words from the file. + */ + public final Set<String> getWords() + { + return Collections.unmodifiableSet(wordMap.keySet()); + } + + /** + * Returns the count of a word in a file. + * + * @param word + * The file to be counted. + * @return Returns the count of findings in the file. + */ + public final int getCount(String word) + { + if (word == null) + { + throw new IllegalArgumentException("Word must be a valid referece."); + } + if (word.isEmpty()) + { + throw new IllegalArgumentException("The word can't be empty."); + } + + Integer tmp = wordMap.get(word); + if (tmp == null) + { + return 0; + } + return tmp; + } + } |
