Sinux1

PS7Q3

Oct 20th, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import java.util.Scanner;
  6.  
  7. public class Q3 {
  8.  
  9.     private static Scanner kb;
  10.     private static Scanner fs;
  11.    
  12.     private static HashMap<String, Integer> mappings;
  13.    
  14.     public static File openFile(String input)
  15.     {
  16.         System.out.println("Opening " + input);
  17.         File f = new File(input);
  18.         return f;
  19.     }
  20.    
  21.     public static void countUnique(File input, HashMap<String, Integer> map)
  22.     {
  23.         try
  24.         {
  25.             fs = new Scanner(input);
  26.             while(fs.hasNext())
  27.             {
  28.                 String temp = fs.next();
  29.                 // If this map already contains the word
  30.                 if(map.containsKey(temp))
  31.                     {
  32.                         // Increment the integer value associated with the key
  33.                         // and add it back in their (an already existing key
  34.                         // is over ridden with the new value of the key
  35.                         int newValue = map.get(temp) + 1;
  36.                         map.put(temp, newValue);
  37.                     }
  38.                 else
  39.                 {
  40.                     map.put(temp, 1);
  41.                 }
  42.                    
  43.             }
  44.            
  45.         } catch (FileNotFoundException e) {
  46.             System.out.println("Error - file not found");
  47.             e.printStackTrace();
  48.         }
  49.     }
  50.    
  51.     public static String mostUsedWord(HashMap<String, Integer> map)
  52.     {
  53.         String mostUsed = null;
  54.         int maxValue = 0;
  55.         for(String key: map.keySet())
  56.         {
  57.             if(key.length() > 5 && map.get(key) >= maxValue)
  58.             {
  59.                 mostUsed = key;
  60.                 maxValue = map.get(key);
  61.             }
  62.         }
  63.         return mostUsed;
  64.     }
  65.    
  66.     public static void main(String[] args)
  67.     {
  68.         kb = new Scanner(System.in);
  69.        
  70.         System.out.println("Enter a file name");
  71.         File inputFile = openFile(kb.next());
  72.        
  73.         mappings = new HashMap<String, Integer>();
  74.         countUnique(inputFile, mappings);
  75.        
  76.         System.out.println("Most common word");
  77.         System.out.println(mostUsedWord(mappings) + " -> " +
  78.                 mappings.get(mostUsedWord(mappings)));
  79.        
  80.     }
  81.  
  82. }
Add Comment
Please, Sign In to add comment