import java.util.ArrayList; import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; /* WordsInReverse.java ** Java application having as its purpose to illustrate the use of the ** ArrayList class. ** ** It reads lines of text from the input source (either a file or the ** keyboard, depending upon whether or not, respectively, a file name ** is provided via a command line argument) and prints the tokens in ** each line in reverse order. For example if a line of input were ** ** The cat in the hat ate a rat. ** ** what would be printed is ** ** rat. a ate hat the in cat The ** ** End of input is indicated by a line having no characters. */ public class WordsInReverse { public static void main(String[] args) throws FileNotFoundException { Scanner input; boolean echo; if (args.length != 0) { // command line arg is input file name input = new Scanner(new File(args[0])); echo = true; } else { input = new Scanner(System.in); echo = false; } System.out.print("> "); String inputLine = input.nextLine(); while (inputLine.length() != 0) { if (echo) { System.out.println(inputLine); } // Create a Scanner to parse the line of tokens just read in Scanner lineScanner = new Scanner(inputLine); // Get an ArrayList containing the tokens on the just-read input line. ArrayList tokens = tokenList(lineScanner); // Reverse the order of the tokens in the list. reverseList(tokens); // Print the list's elements. for (int k = 0; k != tokens.size(); k++) { System.out.printf("%s ", tokens.get(k)); } // Print prompt for next line of input, and then read it. System.out.print("\n\n> "); inputLine = input.nextLine(); } System.out.println("Goodbye."); } /* Returns a new ArrayList containing all the tokens readable by ** the given Scanner, in the same order that the Scanner reads them. */ private static ArrayList tokenList(Scanner scanner) { // Create an ArrayList to store the tokens. Note that specifying a // length (by passing an int parameter to the constructor) is optional // and is a good idea if you have a good idea as to the size to which // the list will grow. Here we have no idea. ArrayList result = new ArrayList(); // Read each token and store it in the ArrayList. // The add() method adds the specified element onto the end of the list. while (scanner.hasNext()) { String token = scanner.next(); result.add(token); } return result; } /* Reverses the order of the elements in the given ArrayList. ** Note that there is no need to specify the type of elements in the ** list because it is irrelevant here. */ private static void reverseList(ArrayList list) { int left = 0, right = list.size()-1; while (left < right) { // Swap the elements at positions left and right of the list. Object temp = list.get(left); list.set(left, list.get(right)); list.set(right, temp); // Move 'left' and 'right' one place towards the middle of the list. left = left + 1; right = right - 1; } } }