package chapter4;
import java.util.Scanner;
public class PostFix {
/**
* @后缀表达式的计算
* 不足之处:这段程序只是有栈表示了后缀表达式的计算,但是计算的参数却只能在0到9之间,所以要考虑引入集合函数。
*/
public static void main(String[] args) {
while(true){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
ParsePost post = new ParsePost(input);
int output = post.doParse();
System.out.println(output);
}
}
}
class StackB{
private int maxSize;
private int[] theStack;
private int top;
public StackB(int max){
maxSize = max;
theStack = new int[maxSize];
top=-1;
}
public void push(int value){
theStack[++top] = value;
}
public int pop(){
return theStack[top--];
}
public int peek(){
return theStack[top];
}
public boolean isEmpty(){
return top==-1;
}
public boolean isFull(){
return top==maxSize-1;
}
public int size(){
return top+1;
}
}
class ParsePost{
private String input;
private StackB theStack;
public ParsePost(String in){
input = in;
theStack = new StackB(input.length());
}
public int doParse(){
int intterNum;
for(int i=0;i<input.length();i++){
char ch = input.charAt(i);
if(ch>='0' && ch<='9')
theStack.push((int)(ch-'0'));
else{
int num1 = theStack.pop();
int num2 = theStack.pop();
switch(ch){
case '+':
intterNum = num1+num2;
break;
case '-':
intterNum = num1-num2;
break;
case '*':
intterNum = num1*num2;
break;
case '/':
intterNum = num1/num2;
break;
default:
intterNum=0;
break;
}
theStack.push(intterNum);
}
}
intterNum = theStack.pop();
return intterNum;
}
}