Java Reference
In-Depth Information
we have the general operator case, which is succinctly described by the code
in lines 27-31.
A simple
main
routine is given in Figure 11.22. It repeatedly reads a line
of input, instantiates an
Evaluator
object, and computes its value.
11.2.4
expression trees
In an
expression
tree,
the leaves
contain operands
and the other
nodes contain
operators.
Figure 11.23 shows an example of an
expression tree,
the leaves of which are
operands (e.g., constants or variable names) and the other nodes contain
operators. This particular tree happens to be binary because all the operations
are binary. Although it is the simplest case, nodes can have more than two
children. A node also may have only one child, as is the case with the unary
minus operator.
1
/**
2
* Simple main to exercise Evaluator class.
3
*/
4
public static void main( String [ ] args )
5
{
6
String str;
7
Scanner in = new Scanner( System.in );
8
9
System.out.println( “Enter expressions, one per line:” );
10
while( in.hasNextLine( ) )
11
{
12
str = in.nextLine( );
13
System.out.println( “Read: “ + str );
14
Evaluator ev = new Evaluator( str );
15
System.out.println( ev.getValue( ) );
16
System.out.println( “Enter next expression:” );
17
}
18
}
figure 11.22
A simple
main
for
evaluating
expressions
repeatedly
figure 11.23
Expression tree for
(a+b)*(a-b)
*
_
+
a
a
b
b
Search WWH ::
Custom Search