import java.io.*; // Needed to use File and FileNotFoundException classes import java.util.*; // Needed for classes like Scanner, ArrayList, HashMap, Collection, etc. /** * A Java class with a static doPrintNames method that acts like the printNames * function in printNames.py. * * Invoking the main method of this class on command line arguments behaves like * invoking printNames.py on command line arguments. * * This class does *not* have have any instance variales or methods or * (nontrivial) constructor methods. It is not expected that instances of this * class will be created. Rather, this class is just a respository for * the doPrintNames static method corresponding to the Python printNames function. * */ public class printNames { /** * This Java static method should have the same behavior as the Python printNames function * in printNames.py. * * @param filename The relative pathname of a file of first and last names * @param numEntries A positive integer indicating the number of entries to be displayed * */ public static void doPrintNames(String filename, int numEntries) throws FileNotFoundException { Scanner reader = new Scanner(new File(filename)); // reader is object that reads lines of file HashMap> nameDict = new HashMap>(); // nameDict is dictionary associating first name with list of all last names it appears // with in file (including duplicates) while (reader.hasNextLine()) { String line = reader.nextLine(); String [] names = line.split("\\s+"); // split on whitespace String first = names[0]; String last = names[1]; ArrayList lastNameList; if (!nameDict.containsKey(first)) { // Create empty lastNameList and associated it with first name key lastNameList = new ArrayList(); nameDict.put(first,lastNameList); } else { // Find existing lastNameList associated with first name key lastNameList = nameDict.get(first); } // Add last name to lastNameList associated with first name key lastNameList.add(last); } // Convert the set of entries into an ArrayList so that we can use Collections.sort on it. List>> entriesList = new ArrayList>>(nameDict.entrySet()); // Uncomment this line for testing // System.out.println(entriesList.size()); // Complete this program skelton so that it behaves like printNames.py // Feel free to define any extra methods or classes that you find useful. } public static void main (String[] args) { if (args.length != 2) { System.out.println("Usage: java printNames "); for (String s : args) { System.out.println(s); } } else { String filename = args[0]; int numEntries = Integer.parseInt(args[1]); try { doPrintNames(filename, numEntries); } catch (FileNotFoundException e) { System.out.println("There is no file named " + filename); } } } }