publicintcalculate(){ if (mExpression == null){ mExpression = ""; }
mExpStack = new Stack<>(); int value = 0; Constant left, right; for (char c : mExpression.toCharArray()){ switch (c){ case'+': right = new Constant(pop()); left = new Constant(pop()); Plus plus = new Plus(left, right); value = plus.interpreter(this); break; case'-': right = new Constant(pop()); left = new Constant(pop()); Minus minus = new Minus(left, right); value = minus.interpreter(this); break; case'*': right = new Constant(pop()); left = new Constant(pop()); Multiply multiply = new Multiply(left, right); value = multiply.interpreter(this); break; case'0': case'1': case'2': case'3': case'4': case'5': case'6': case'7': case'8': case'9': value = c - '0'; break; default: break; } mExpStack.push(value); } return pop(); }
public Integer pop(){ return mExpStack.pop(); } }
// 5. Test publicclassTestInterpreter{ publicstaticvoidmain(String[] args){ Context context = new Context("5364-*+"); int value = context.calculate(); System.out.println("value = " + value); } }