Java Reference
In-Depth Information
For the sample file, this code would read the line
"
this
"
into the variable
line
and leave you with the following three lines of text in the
Scanner
:
is
fun
no?
Recall that your aim is to produce the following overall output:
no?
fun
is
this
You might be asking yourself questions like, “Is there another line of input to
process?” But that's not recursive thinking. If you're thinking recursively, you'll be
thinking about what a call on the method will get you. Since the
Scanner
is positioned
in front of the three lines
"
is
"
,
"
fun
"
, and
"
no?
"
, a call on
reverse
should read in
those lines and produce the first three lines of output that you're looking for. If that
works, you'll only have to write out the line
"
this
"
afterwards to complete the output.
This is where the leap of faith comes in—you have to believe that the
reverse
method actually works. If it does, this code can be completed as follows:
public static void reverse(Scanner input) {
if (input.hasNextLine()) {
// recursive case (nonempty file)
String line = input.nextLine();
reverse(input);
System.out.println(line);
}
}
This code does work. To reverse a sequence of lines, simply read in the first one,
reverse the others, and then write out the first one.
Novices seem to understand recursion better when they know more about the underly-
ing mechanics that make it work. Before we examine a recursive method in detail, let's
review how nonrecursive methods work. Consider the following simple program:
1 // Simple program that draws three triangles.
2
public class
DrawTriangles {
3
public static void
main(String[] args) {
4 drawTriangle();
5 drawTwoTriangles();
Search WWH ::
Custom Search