class GenericStack {
private java.util.ArrayList list=new java.util.ArrayList();
public int getSize(){
return list.size();
}
public E peek(){
return list.get(getSize()-1);
}
public void push(E o){
list.add(o);
}
public E pop(){
E o=list.get(getSize()-1);
list.remove(getSize()-1);
return o;
}
public boolean isEmpty()
{
return list.isEmpty();
}
}
public class EvaluateExpression{
public static void main(String[] args){
String expression="(3-2)*6+9/3";
try{
System.out.println(expression+"="+evaluateexpression_r(expression));
}catch(Exception ex){
System.out.println("wrong expression!");
}
}
public static int evaluateexpression_r(String expression){
GenericStackoperandStack=new GenericStack();
GenericStackoperatiorStack=new GenericStack();
java.util.StringTokenizer tokens=new java.util.StringTokenizer(expression,"()+-/*",true);
while(tokens.hasMoreTokens())
{
String token=tokens.nextToken().trim();
// System.out.println(token);
if(token.length()==0){
continue;
}
else if(token.charAt(0)=='+'||token.charAt(0)=='-'){
while(!operatiorStack.isEmpty() &&(operatiorStack.peek()=='+'||
operatiorStack.peek()=='-'||
operatiorStack.peek()=='*'||
operatiorStack.peek()=='/'))
{
processAnOperator(operandStack,operatiorStack);
}
operatiorStack.push(token.charAt(0));
}
else if(token.charAt(0)=='*'|| token.charAt(0)=='/'){
while(!operatiorStack.isEmpty() &&(
operatiorStack.peek()=='*'||
operatiorStack.peek()=='/')){
processAnOperator(operandStack,operatiorStack);
}
operatiorStack.push(token.charAt(0));
}
else if(token.trim().charAt(0)=='('){
operatiorStack.push('(');
}
else if(token.trim().charAt(0)==')'){
while(operatiorStack.peek()!='('){
processAnOperator(operandStack,operatiorStack);
}
operatiorStack.pop();
}
else{
operandStack.push(new Integer(token));
}
}
while(!operatiorStack.isEmpty()){
processAnOperator(operandStack,operatiorStack);
}
return operandStack.pop();
}
public static void processAnOperator(GenericStack operandStack,GenericStackoperatiorStack){
char op=operatiorStack.pop();
int op1=operandStack.pop();
int op2=operandStack.pop();
if(op=='+')
operandStack.push(op2+op1);
if(op=='-')
operandStack.push(op2-op1);
if(op=='*')
operandStack.push(op2*op1);
if(op=='/')
operandStack.push(op2/op1);
}
}