Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Scanner;
- public class Q3 {
- private static Scanner kb;
- private static Scanner fs;
- private static HashMap<String, Integer> mappings;
- public static File openFile(String input)
- {
- System.out.println("Opening " + input);
- File f = new File(input);
- return f;
- }
- public static void countUnique(File input, HashMap<String, Integer> map)
- {
- try
- {
- fs = new Scanner(input);
- while(fs.hasNext())
- {
- String temp = fs.next();
- // If this map already contains the word
- if(map.containsKey(temp))
- {
- // Increment the integer value associated with the key
- // and add it back in their (an already existing key
- // is over ridden with the new value of the key
- int newValue = map.get(temp) + 1;
- map.put(temp, newValue);
- }
- else
- {
- map.put(temp, 1);
- }
- }
- } catch (FileNotFoundException e) {
- System.out.println("Error - file not found");
- e.printStackTrace();
- }
- }
- public static String mostUsedWord(HashMap<String, Integer> map)
- {
- String mostUsed = null;
- int maxValue = 0;
- for(String key: map.keySet())
- {
- if(key.length() > 5 && map.get(key) >= maxValue)
- {
- mostUsed = key;
- maxValue = map.get(key);
- }
- }
- return mostUsed;
- }
- public static void main(String[] args)
- {
- kb = new Scanner(System.in);
- System.out.println("Enter a file name");
- File inputFile = openFile(kb.next());
- mappings = new HashMap<String, Integer>();
- countUnique(inputFile, mappings);
- System.out.println("Most common word");
- System.out.println(mostUsedWord(mappings) + " -> " +
- mappings.get(mostUsedWord(mappings)));
- }
- }
Add Comment
Please, Sign In to add comment