// Kyle Thayer, CSE 142 // This program reads in a file and prints out the words in reverse order, // with each word on a new line. import java.util.*; import java.io.*; public class ReverseFile { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("words.txt")); // Bad version with an array: 100 words is too short, // and trying to guess the size of a file is not always possible /* String[] allWords = new String[100]; int wordCount = 0; while (input.hasNext()) { String word = input.next(); allWords[wordCount] = word; wordCount++; } for(int i = wordCount - 1; i >= 0; i--) { System.out.println(allWords[i] + " "); } */ // start with an empty ArrayList of Strings ArrayList words = new ArrayList(); // add all the words in the file to the ArrayList while (input.hasNext()) { String word = input.next(); words.add(word); } // go over the ArrayList backward, printing out each word for (int i = words.size() - 1; i >= 0; i--) { System.out.println(words.get(i)); } } }