import java.util.Stack;publicclass 栈的表达式计算 {publicstaticvoidmain(String[] args){
Stack<Integer> number =newStack<Integer>();
Stack<Character> fuhao =newStack<Character>();
String ex ="77*2+3+4+10/5";int index =0;int num1 =0;int num2 =0;char c =' ';while(true){// 字符char op = ex.charAt(index);if(isoper(op)==true){//符号栈不为空if(!fuhao.isEmpty()){//如果当前运算符的优先级小于或等于运算符中的优先级,则从符号栈中//取出一个运算符,再从数栈中弹出两个数进行计算,并将计算后的结果,再压入数栈if(youxianji(op)<=youxianji(fuhao.peek())){
num2 = number.pop();
num1 = number.pop();
c = fuhao.pop();
number.push(cul(num1, num2, c));
fuhao.push(op);}else{//符号栈为空,直接入栈
fuhao.push(op);}}else{//如果当前运算符的优先级大于运算符中的优先级,直接入栈
fuhao.push(op);}
index ++;}// 数字else{
String num ="";//解决数字是多位数的情况while(!isoper((ex.charAt(index)))){
num = num +(ex.charAt(index)-48);
index = index +1;//为了处理表达式最末尾的情况,到末尾后已经没有操作数了,终止循环if(index>=ex.length()){break;}}//数字入栈
number.push(Integer.parseInt(num));}if(index>=ex.length()){break;}}while(true){if(fuhao.isEmpty()){break;}else{
num2 = number.pop();
num1 = number.pop();
c = fuhao.pop();
number.push(cul(num1, num2, c));}}
System.out.println(number.peek());}publicstaticbooleanisoper(int i){if(i =='+'|| i =='-'|| i =='*'|| i =='/'){returntrue;}else{returnfalse;}}// 判断优先级publicstaticintyouxianji(char c){if(c =='*'|| c =='/'){return1;}elseif(c =='+'|| c =='-'){return0;}else{return-1;}}publicstaticintcul(int num1,int num2,char c){int res =0;switch(c){case'+':
res = num1 + num2;break;case'-':
res = num1 - num2;break;case'*':
res = num1 * num2;break;case'/':
res = num1 / num2;break;default:break;}return res;}}