Java Reference
In-Depth Information
boolean done = false;
while (!done)
{
String next = tokenizer.peekToken();
if ("+".equals(next) || "-".equals(next))
{
tokenizer.nextToken(); // Discard "+" or
"-"
int value2 = getTermValue();
if ("+".equals(next)) value = value +
value2;
else value = value - value2;
}
else done = true;
}
return value;
}
The
getTermValue
method calls
getFactorValue
in the same way,
multiplying or dividing the factor values.
Finally, the
getFactorValue
method checks whether the next input is a number,
or whether it begins with a
(
token. In the first case, the value is simply the value of
the number. However, in the second case, the
getFactorValue
method makes a
recursive call to
getExpressionValue
. Thus, the three methods are mutually
recursive.
public int getFactorValue()
{
int value;
String next = tokenizer.peekToken();
if ("(".equals(next))
{
tokenizer.nextToken(); // Discard "("
value = getExpressionValue();
tokenizer.nextToken(); // Discard ")"
}
else
value =
Integer.parseInt(tokenizer.nextToken());
return value;
}
613
614
To see the mutual recursion clearly, trace through the expression
(3+4)*5
: