package algortest;
/*
* 思路1:定义一个char型变量以单个字符为单位从键盘接受一个字符,然而java只能从键盘接受String
* 型的字符串,此方法实行起来较为困难
*
* 思路2:定义一个String型变量,先从键盘把要计算的表达式全部接收(比如:123*(8-9))
* 然后再逐一的扫描改表达式字符串,该方法可行!
*
*/
import java.util.Scanner;
import java.util.Stack;
public class Biaodashi {
//private static String str="";
public static char compare(char i,char j){
if((i=='#'&&j!='#')||(i=='('&&j!=')')||(j=='('&&i!=')'))return '<';
else if((i=='+'||i=='-')&&(j=='*')||j=='/')return '<';
else if((i=='('&&j==')')||(i=='#'&&j=='#'))return '=';
else return '>';
}
public static int oper(int a,char b,int c){
switch(b){
case '+':
return a+c;//是a+c!不是a+b!!!
case '-':
return a-c;
case '*':
return a*c;
case '/':
return a/c;
default:return 0;
}
//return 0;
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String str=sc.nextLine();//接收整个表达式字符串
str+="##";//防止越界多加了一个‘#’
Stack optr=new Stack();
Stack num=new Stack();
optr.push('#');//符号入栈!!&&str.charAt(t)!='#'
//char ch=sc.nextLine().charAt(0);
int t=0;//出现栈为空,数组越界等看循环条件是否正确!
while((t<str.length()-1&&str.charAt(t)!='#')||(char)optr.peek()!='#'){
if('0'<=str.charAt(t)&&str.charAt(t)<='9'){
String numb="";
while('0'<=str.charAt(t)&&str.charAt(t)<='9')
numb+=str.charAt(t++);
num.push(Integer.parseInt(numb));//数字入栈
}
else
switch(compare((char)optr.peek(),str.charAt(t))){
case '<':
char ch=str.charAt(t);
optr.push(ch);//符号入栈
t++;
break;
case '>':
char oper=(char)optr.pop();
//if(!num.empty()){
int b=(int) num.pop(),a=(int) num.pop();//数字连续出栈
int c=oper(a,oper,b);
num.push(c);
//t++;
//}
break;
case '=':
optr.pop();
t++;
break;
}
}
System.out.println(num.peek());
}
}
}