Java Reference
In-Depth Information
1 /**
2 * Find the next token, skipping blanks, and return it.
3 * For VALUE token, place the processed value in currentValue.
4 * Print error message if input is unrecognized.
5 */
6 public Token getToken( )
7 {
8 long theValue;
9
10 if( !str.hasMoreTokens( ) )
11 return new Token( );
12
13 String s = str.nextToken( );
14 if( s.equals( " " ) ) return getToken( );
15 if( s.equals( " ^ " ) ) return new Token( EXP );
16 if( s.equals( "/" ) ) return new Token( DIV );
17 if( s.equals( "*" ) ) return new Token( MULT );
18 if( s.equals( "(" ) ) return new Token( OPAREN );
19 if( s.equals( ")" ) ) return new Token( CPAREN );
20 if( s.equals( "+" ) ) return new Token( PLUS );
21 if( s.equals( "-" ) ) return new Token( MINUS );
22
23 try
24 { theValue = Long.parseLong( s ); }
25 catch( NumberFormatException e )
26 {
27 System.err.println( "Parse error" );
28 return new Token( );
29 }
30
31 return new Token( VALUE, theValue );
32 }
figure 11.16
The getToken routine for returning the next token in the input stream
Figures 11.18 and 11.19 show the routines used to implement the postfix
machine. The routine in Figure 11.18 is used to pop the postfix stack and print
an error message if needed. The binaryOp routine in Figure 11.19 applies topOp
(which is expected to be the top item in the operator stack) to the top two
items on the postfix stack and replaces them with the result. It also pops the
operator stack (at line 33), signifying that processing for topOp is complete.
Figure 11.20 declares a precedence table, which stores the operator pre-
cedences and is used to decide what is removed from the operator stack. The
operators are listed in the same order as the token constants.
A precedence table
is used to decide
what is removed
from the operator
stack. Left-
associative opera-
tors have the
operator stack
precedence set
at 1 higher than the
input symbol
precedence. Right-
associative opera-
tors go the other
way.
 
Search WWH ::




Custom Search