import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; /** * @author gtowell * file: UniqueWords.java * Created: Sep 12, 2019 * Desc: * Read a file then print a list of the unique words contained in that file. * Words are defined as sinly sets of characters separated by whitespace. **/ public class UniqueWords { public static void main(String[] args) { UniqueWords wc = new UniqueWords(); wc.uniquer("UniqueWords.java"); } /** * Open a file and read it word by word * @param filename the name of the file to be opened * No return value, rather the result is the side-effect of printing the list of words in the given file **/ void uniquer(String filename) { ArrayList wordS = new ArrayList<>(); try (Scanner input=new Scanner(new File(filename))){ while (input.hasNextLine()) { // test if there is a line to read String line = input.nextLine(); Scanner s2 = new Scanner(line); while (s2.hasNext()) { String w = s2.next(); if (!findWord(w, wordS)) { wordS.add(w); } } s2.close(); } } catch (FileNotFoundException e) { System.err.println("Error in opening the file:" + filename); System.exit(1); } for (String w : wordS) { System.out.println(w); } } /** * Check arraylist for a word * @param w the word to be looked for * @param words the array list to be check * @return true iff the arraylist contains the word **/ private boolean findWord(String w, ArrayList words) { for (String ww : words) { if (w.equals(ww)) return true; } return false; } }