Java Reference
In-Depth Information
numbers, operators, and parentheses. (For simplicity, we only accept positive integers
as numbers, and we don't allow spaces in the input.)
Figure 4
Syntax Trees for Two Expressions
612
613
When you call
nextToken
, the next input token is returned as a string. We also
supply another method,
peekToken
, which allows you to see the next token without
consuming it. To see why the
peekToken
method is necessary, consider the syntax
diagram of the factor type. If the next token is a
"*"
or
"/"
, you want to continue
adding and subtracting terms. But if the next token is another character, such as a
"+"
or
"Ċ"
, you want to stop without actually consuming it, so that the token can be
considered later.
To compute the value of an expression, we implement three methods:
get-ExpressionValue
,
getTermValue
, and
getFactorValue
. The
getExpressionValue
method first calls
getTermValue
to get the value of the
first term of the expression. Then it checks whether the next input token is one of
+
or
Ċ
. If so, it calls
getTerm-Value
again and adds or subtracts it.
public int getExpressionValue()
{
int value = getTermValue();