import java.io.*; import java.util.*; //HashMap public class WordFrequency { public static void main(String args[]) { if (args.length != 1) { System.err.println("Usage: java WordFrequency "); System.exit(1); } Map words = new HashMap(); //An object that maps keys to values. //A map cannot contain duplicate keys; each key can map to at most one value. String delim = " \t\n.,:;?!-/()[]\"\'+=%$£#@\\"; try { //FileReader: java.io.FileNotFoundException BufferedReader in = new BufferedReader( new FileReader(args[0]) ); String line, word; Count count; try { while ((line = in.readLine()) != null) { // readLine(): IOException - If an I/O error occurs StringTokenizer st = new StringTokenizer(line, delim); while (st.hasMoreTokens()) { word = st.nextToken().toLowerCase(); //nextToken: java.util.NoSuchElementException count = (Count) words.get(word); if (count == null) { words.put(word, new Count(word, 1)); } else { count.i++; } } } } catch (Exception e) { System.err.println(e); } Set set = words.entrySet(); // A collection that contains no duplicate elements. Iterator iter = set.iterator(); Map maxWords = new HashMap(); // max arv sõnu võib olla mitu.. Count maxCount = new Count("", 0); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); //key-value pair word = (String) entry.getKey(); count = (Count) entry.getValue(); if (maxCount.i <= count.i) { if (maxCount.i < count.i) { maxWords = new HashMap(); maxWords.put(word, (maxCount = count)); } else if (maxCount.i == count.i) maxWords.put(word, count); } System.out.println(word + (word.length() < 8 ? "\t\t" : "\t") + count.i); } if (maxWords.size() > 1) { System.out.println("\nKõige sagedamini (" + maxCount.i + ") esinesid järgmised sõnad:"); Iterator maxIter = maxWords.keySet().iterator(); while (maxIter.hasNext()) { System.out.println((String)maxIter.next()); } } else if (maxWords.size() == 1) System.out.println("\nKõige sagedamini (" + maxCount.i + ") esines sõna: " + maxCount.word); else System.out.println("\nFailist \"" + args[0] + "\" ei leitud ühtegi sõna."); } catch (IOException e) { System.out.println(e.getMessage()); } } }