diff --git a/02/MostCommonWord.java b/02/MostCommonWord.java new file mode 100644 index 0000000000000000000000000000000000000000..a066abdbc602d52821468be74c06ba301e0a8c53 --- /dev/null +++ b/02/MostCommonWord.java @@ -0,0 +1,33 @@ +import java.io.File; +import java.io.FileNotFoundException; +import java.util.*; + +public class MostCommonWord { + private static final String BOOK_FILENAME = "alice.txt"; + + public static void main(String[] args) throws FileNotFoundException { + // NOTE: This is wrong...do not copy. + // keys are words + // values are number of times that word occurs + Map<String, Integer> map = new HashMap<>(); + Scanner s = new Scanner(new File(BOOK_FILENAME)); + while (s.hasNext()) { + String next = s.next(); + if (!map.containsKey(next)) { + map.put(next, 0); + } + int oldValue = map.get(next); + map.put(next, oldValue + 1); + // map.get(next) = map.get(next) + 1 + } + // print size of map + String best = "???"; + for (String key : map.keySet()) { + if (map.get(best) == null || map.get(key) > map.get(best)) { + best = key; + } + // ... implement together + } + System.out.println(best); + } +}