import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; /** * Program to print longest words found in file. * */ public class LongestWords { /** Order by String length in ascending order. */ public static class MinLengthComparator implements Comparator { public int compare(String s, String t) { return Integer.compare(s.length(), t.length()); } } public static void main(String[] args) { if (args.length != 2) { System.err.println("Usage: java LongestWords N INPUTFILE"); System.exit(1); } // Process command line arguments. int N = Integer.parseInt(args[0]); String filename = args[1]; // Open input file. FileReader reader = null; try { reader = new FileReader(filename); } catch (FileNotFoundException e) { System.err.println("Error: file " + filename + " not found."); System.exit(1); } // Create queue ordered by length (ascending), with initial capacity N. PriorityQueue queue = new PriorityQueue(N, new MinLengthComparator()); // Read and process all words in file. Scanner scanner = new Scanner(reader); while (scanner.hasNext()) { String word = scanner.next(); // Insert word in queue if it's long enough ... } } }