Java Reference
In-Depth Information
L ISTING 20.9
EvaluateExpression.java
1 import java.util.Stack;
2
3 public class EvaluateExpression {
4 public static void main(String[] args) {
5 // Check number of arguments passed
6 if (args.length != 1 ) {
7 System.out.println(
8 "Usage: java EvaluateExpression \"expression\"" );
9 System.exit( 1 );
10 }
11
12 try {
13 System.out.println(evaluateExpression(args[ 0 ]));
14 }
15 catch (Exception ex) {
16 System.out.println( "Wrong expression: " + args[ 0 ]);
17 }
18 }
19
20 /** Evaluate an expression */
21 public static int evaluateExpression(String expression) {
22 // Create operandStack to store operands
23 Stack<Integer> operandStack = new Stack<>();
24
25 // Create operatorStack to store operators
26 Stack<Character> operatorStack = new Stack<>();
27
28 // Insert blanks around (, ), +, -, /, and *
29 expression = insertBlanks(expression);
30
31
check usage
evaluate expression
exception
operandStack
operatorStack
prepare for extraction
// Extract operands and operators
32
String[] tokens = expression.split( " " );
extract tokens
33
34 // Phase 1: Scan tokens
35 for (String token: tokens) {
36 if (token.length() == 0 ) // Blank space
37 continue ; // Back to the while loop to extract the next token
38 else if (token.charAt( 0 ) == '+' || token.charAt( 0 ) == '-' ) {
39 // Process all +, -, *, / in the top of the operator stack
40 while (!operatorStack.isEmpty() &&
41 (operatorStack.peek() == '+' ||
42 operatorStack.peek() == '-' ||
43 operatorStack.peek() == '*' ||
44 operatorStack.peek() == '/' )) {
45 processAnOperator(operandStack, operatorStack);
46 }
47
48 // Push the + or - operator into the operator stack
49 operatorStack.push(token.charAt( 0 ));
50 }
51 else if (token.charAt( 0 ) == '*' || token.charAt( 0 ) == '/' ) {
52 // Process all *, / in the top of the operator stack
53 while (!operatorStack.isEmpty() &&
54 (operatorStack.peek() == '*' ||
55 operatorStack.peek() == '/' )) {
56 processAnOperator(operandStack, operatorStack);
57 }
58
process tokens
+ or - scanned
* or / scanned
 
 
Search WWH ::




Custom Search