求值的过程即手算的过程。
逐字符扫描表达式,遇到运算数将其入栈,遇到运算符时就作用于从栈中弹出的两个操作数再并将结果入栈。扫描完整个表达式时,栈中的数即为表达式的结果。
package stack;
import java.util.Stack;
/**
* 后缀表达式求值
*/
public class Stack01 {
public static int start = 0;
public static void calc(String s) {
Stack stack = new Stack();
String token;
while ((token = getToken(s)) != null) {
int res=0;
try {
//运算数
res = Integer.parseInt(token);
} catch (NumberFormatException e) {
//运算符
int num2 = (int)stack.pop();
int num1 = (int)stack.pop();
res = op(num1,num2,token);
} finally {
stack.push(res);
}
}
System.out.println(stack.peek());
}
private static int op(int num1, int num2, String oprand) {
int res;
switch (oprand) {
case "+":
res = num1 + num2;
break;
case "-":
res = num1 - num2;
break;
case "*":
res = num1 * num2;
break;
case "/":
res = num1 / num2;
break;
default:
res = 0;
}
return res;
}
private static String getToken(String s) {
int len = s.length();
if (start == len) {
return null;
}
if (start == len-1) {
int temp = start;
start++;
return s.substring(temp);
}
int end = start;
char ch = s.charAt(end);
while (ch != ' ') {
end++;
ch = s.charAt(end);
}
String token = s.substring(start, end);
start = end + 1;
return token;
}
public static void main(String[] args) {
calc("10 10 + 2 *");
System.out.println();
}
}