Java Reference
In-Depth Information
59 // Push the * or / operator into the operator stack
60 operatorStack.push(token.charAt( 0 ));
61 }
62 else if (token.trim().charAt( 0 ) == '(' ) {
63 operatorStack.push( '(' ); // Push '(' to stack
64 }
65 else if (token.trim().charAt( 0 ) == ')' ) {
66 // Process all the operators in the stack until seeing '('
67 while (operatorStack.peek() != '(' ) {
68 processAnOperator(operandStack, operatorStack);
69 }
70
71 operatorStack.pop(); // Pop the '(' symbol from the stack
72 }
73
( scanned
) scanned
else { // An operand scanned
74
// Push an operand to the stack
75
operandStack.push( new Integer(token));
an operand scanned
76 }
77 }
78
79 // Phase 2: Process all the remaining operators in the stack
80 while (!operatorStack.isEmpty()) {
81 processAnOperator(operandStack, operatorStack);
82 }
83
84
clear operatorStack
// Return the result
85
return operandStack.pop();
return result
86 }
87
88 /** Process one operator: Take an operator from operatorStack and
89 * apply it on the operands in the operandStack */
90 public static void processAnOperator(
91 Stack<Integer> operandStack, Stack<Character> operatorStack) {
92 char op = operatorStack.pop();
93 int op1 = operandStack.pop();
94 int op2 = operandStack.pop();
95 if (op == '+' )
96 operandStack.push(op2 + op1);
97 else if (op == '-' )
98 operandStack.push(op2 - op1);
99 else if (op == '*' )
100 operandStack.push(op2 * op1);
101 else if (op == '/' )
102 operandStack.push(op2 / op1);
103 }
104
105 public static String insertBlanks(String s) {
106 String result = "" ;
107
108 for ( int i = 0 ; i < s.length(); i++) {
109 if (s.charAt(i) == '(' || s.charAt(i) == ')' ||
110 s.charAt(i) == '+' || s.charAt(i) == '-' ||
111 s.charAt(i) == '*' || s.charAt(i) == '/' )
112 result += " " + s.charAt(i) + " " ;
113 else
114 result += s.charAt(i);
115 }
116
117
process +
process -
process *
process /
insert blanks
return result;
118 }
119 }
 
Search WWH ::




Custom Search