Java Reference
In-Depth Information
two numbers (say, + , 3.4 , and 2.6 ). It would be nice if we could just write a state-
ment like the following:
return operand1 operator operand2; // does not work
Unfortunately, Java doesn't work that way. We have to use a nested if/else state-
ment to test what kind of operator we have and to return an appropriate value:
if (operator.equals("+")) {
return operand1 + operand2;
} else if (operator.equals("-")) {
return operand1 - operand2;
} else if (operator.equals("*")) {
...
We can include this code in its own method so that our recursive method stays
fairly short:
public static double evaluate(Scanner input) {
if (input.hasNextDouble()) {
// base case with a simple number
return input.nextDouble();
} else {
// recursive case with an operator and two operands
String operator = input.next();
double operand1 = evaluate(input);
double operand2 = evaluate(input);
return apply(operator, operand1, operand2);
}
}
Complete Program
When you program with recursion, you'll notice two things. First, the recursive code
that you write will tend to be fairly short, even though it might be solving a very
complex task. Second, most of your program will generally end up being supporting
code for the recursion that does low-level tasks. For our current task of evaluating a
prefix expression, we have a short and powerful prefix evaluator, but we need to
include some supporting code that explains the program to the user, prompts for a
prefix expression, and reports the result. We also found that we needed a method that
would apply an operator to two operands. The nonrecursive parts of the program are
fairly straightforward, so they are included in the following code without detailed
discussion:
1 // This program prompts for and evaluates a prefix expression.
2
 
Search WWH ::




Custom Search