Java Reference
In-Depth Information
To perform this task iteratively, you'd need some kind of data structure for storing
the lines of text, such as an ArrayList<String> . However, recursion allows you to
solve the problem without using a data structure.
Remember that recursive programming involves thinking about cases. What would
be the simplest file to reverse? A one-line file would be fairly easy to reverse, but it
would be even easier to reverse an empty file. So, you can begin writing your method
as follows:
public static void reverse(Scanner input) {
if (!input.hasNextLine()) {
// base case (empty file)
...
} else {
// recursive case (nonempty file)
...
}
}
In this problem, the base case is so simple that there isn't anything to do. An
empty file has no lines to reverse. Thus, in this case it makes more sense to turn
around the if/else statement so that you test for the recursive case. That way you
can write a simple if statement that has an implied “ else there is nothing to do”:
public static void reverse(Scanner input) {
if (input.hasNextLine()) {
// recursive case (nonempty file)
...
}
}
Again, the challenge is to solve only a little bit of the problem. How do you take
just one step that will get you closer to completing the task? You can read one line of
text from the file:
public static void reverse(Scanner input) {
if (input.hasNextLine()) {
// recursive case (nonempty file)
String line = input.nextLine();
...
}
}
 
Search WWH ::




Custom Search