import java.util.*; interface Expression{ public Stack<String> InterpretAction(Stack<String> exp); } class MinusInterpret implements Expression { @Override public Stack<String> InterpretAction(Stack<String> exp) { int result=-Integer.parseInt(exp.pop())+Integer.parseInt(exp.pop()); exp.push(String.valueOf(result)); return exp; } } class PlusInterpret implements Expression { @Override public Stack<String> InterpretAction(Stack<String> exp) { int result=Integer.parseInt(exp.pop())+Integer.parseInt(exp.pop()); exp.push(String.valueOf(result)); return exp; } } class IntInterpret implements Expression { private int number; public IntInterpret(int num){ this.number=num; } @Override public Stack<String> InterpretAction(Stack<String> exp) { exp.push(String.valueOf(this.number)); return exp; } } /** * @see http://en.wikipedia.org/wiki/Interpretter_Pattern * @author root * */ public class interrupter { /** * @param args */ public static void main(String[] args) { String str="42 4 2 - +"; Stack<String> expre=new Stack<String>(); for(String s:str.split(" ")){ if(s.equalsIgnoreCase("+")) expre=new PlusInterpret().InterpretAction(expre); else if(s.equalsIgnoreCase("-")) expre=new MinusInterpret().InterpretAction(expre); else expre=new IntInterpret(Integer.parseInt(s)).InterpretAction(expre); } System.out.println(expre.pop()); } }