// CSE 143, Winter 2012 // This program demonstrates usage of an ArrayList to store data. // It filters out plurals and prints the words of a file in reverse order. import java.io.*; import java.util.*; public class ReverseFile { public static void main(String[] args) throws FileNotFoundException { ArrayList words = readFile("words.txt"); filterPlurals(words); printReverse(words); // printReverse(readFile("tas.txt")); } // Reads the entire contents of the given file and // stores them into a list, which is returned. // Assumes that the file exists. public static ArrayList readFile(String fileName) throws FileNotFoundException { ArrayList words = new ArrayList(); Scanner input = new Scanner(new File(fileName)); while (input.hasNext()) { words.add(input.next()); } return words; } // Removes all plural words (ones that end with "s") // from the given list of strings. public static void filterPlurals(ArrayList words) { for (int i = 0; i < words.size(); i++) { String word = words.get(i); if (word.endsWith("s")) { words.remove(i); i--; } } } // Prints the elements of the given list, one per line, in reverse order. public static void printReverse(ArrayList words) { System.out.println(words); for (int i = words.size() - 1; i >= 0; i--) { System.out.println(words.get(i)); } } }