Java Reference
In-Depth Information
Suppose that we call this method with the earlier sample input file, which contains
the following four lines of text:
this
is
fun
no?
When we call the method, it reads the first line of text into its line variable, and
then it reaches the recursive call on reverse :
public static void reverse(Scanner input) {
if (input.hasNextLine()) {
String line = input.nextLine();
reverse(input);
System.out.println(line);
}
}
line "this"
Then what happens? In the DrawTriangles program, we took the sheet of paper
for the method being called and placed it on top of the current sheet of paper. But
here we have the method reverse calling the method reverse . To understand what
happens, you have to realize that each method invocation is independent of the oth-
ers. We don't have only a single sheet of paper with the reverse method written on
it; we have as many copies as we want. So, we can grab a second copy of the method
definition and place it on top of the current one:
public static void reverse(Scanner input) {
if (input.hasNextLine()) {
public static void reverse(Scanner input) {
if (i nput.hasNextLine()) {
String line = input.nextLine();
reverse(input);
System.out.println(line);
}
}
line
String line - input.nextLine(),
reverse(input),
System.out.println(line),
}
}
line “this”
This new version of the method has a variable of its own, called line , in which it
can store a line of text. Even though the previous version (the one underneath this
one) is in the middle of its execution, this new one is at the beginning of its execu-
tion. Think back to the analogy of being able to employ an entire army of people to
write out a line of stars. Just as you could call on as many people as you needed to
solve that problem, you can bring up as many copies of the reverse method as you
need to solve this problem.
 
Search WWH ::




Custom Search