// CSE 143, Winter 2009, Marty Stepp // This program uses recursion to print the lines of a file in reverse order. import java.io.*; import java.util.*; public class Poem { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("poem.txt")); reverseLines(input); } // Prints the lines of the given input file in reverse order, recursively. public static void reverseLines(Scanner input) { if (input.hasNextLine()) { // recursive case: one or more lines; reverse them // (the base case is implicitly to do nothing) String line = input.nextLine(); // read first line reverseLines(input); // print rest of lines, reversed System.out.println(line); // print first line last } } // original version; also works but does not have "recursion zen" public static void reverseLines2(Scanner input) { String line = input.nextLine(); // read first line if (!input.hasNextLine()) { // base case (one line file); just print the line System.out.println(line); } else { // recursive case (multi-line file) reverseLines2(input); // print rest of lines, reversed System.out.println(line); // print first line last } } }