Java Reference
In-Depth Information
Now we execute this println , for the text " is " , and eliminate one more call:
public static void reverse(Scanner input) {
if (input.hasNextLine()) {
String line = input.nextLine();
reverse(input);
System.out.println(line);
}
}
line "this"
Notice that we've written out three lines of text so far:
no?
fun
is
Our leap of faith was justified. The recursive call on reverse read in the three
lines of text that followed the first line of input and printed them in reverse order. We
complete the task by printing the first line of text, which leads to this overall output:
no?
fun
is
this
Then this version of the method terminates, and the program has finished executing.
12.3 Recursive Functions and Data
Both of the examples of recursion we have studied so far have been action-oriented
methods with a return type of void . In this section we will examine some of the
issues that arise when you want to write methods that compute values and return a
result. Such methods are similar to mathematical functions in that they accept a set of
input values and produce a set of possible results. We'll also explore an example that
involves manipulating recursive data and an example that requires a helper method.
Integer Exponentiation
Java provides a method called Math.pow that allows you to compute an exponent. If
you want to compute the value of x y , you can call Math.pow(x, y) . Let's consider
how we could implement the pow method. To keep things simple, we'll limit our-
selves to the domain of integers. But because we are limiting ourselves to integers,
we have to recognize an important precondition of our method: We won't be able to
compute negative exponents because the results would not be integers.
 
 
Search WWH ::




Custom Search