public class Calculator { VList varList; //constructor - should only create //the variable list - there is one variable list per calculator //should not assign any stacks here public Calculator () { varList = new VList (); } //assign method public void assign (String line) { //copy line into a character array char[] chars = line.toCharArray (); // get the variable name char var = chars [0]; //and length int len = line.length (); //make it into a substring for calculate/evaluate String expr = line.substring (2, len); //send it to calculate to change to int int val = calculate (expr.toCharArray ()); System.out.println ("Assigning: " + var + "=(" + String.valueOf (expr) + ")" + val); //insert the variable and the value into the vlist varList.insert (var, val); } //public evaluate - converts the string into a char array //and send it to calculate public int evaluate (String expression) { char[] expr = expression.toCharArray (); int val = calculate (expr); System.out.println ("Calculating: " + expression + "=" + val); return val; } //private method to do the work of evaluate private int calculate (char[] expr) { //make a stack to evaluate the postfix expression CStack st = new CStack (); //number of symbols to process is the length of the //string int numSymb = expr.length; //loop though and process each depending on type for (int i = 0; i < numSymb; ++i) { char sym = expr[i]; // if we read an operator //pop and perform calculation //push back onto stack if (isOperator (sym)) { int val1 = st.pop (); int val2 = st.pop (); int val = doOperation (val1, sym, val2); st.push (val); } //if it is a letter - it //is a variable name so we get value and //puch it onto the stack else if (Character.isLetter (sym)) st.push (varList.getValue (sym)); //if it is a number we just push the //actual int it represents onto the stack else if (Character.isDigit (sym)) st.push (Character.digit (sym, 10)); } //finally whatever is leftover is our answer return st.pop (); } //helper method to check if something is an operator public boolean isOperator (char sym) { return ((sym == '+') || (sym == '-') || (sym == '*') || (sym == '/')); } //do operation takes two vals and does the operation // its postfix, values are in reverse order that //is why it is named val2 and val1 in that order public int doOperation (int val2, char oper, int val1) { int ret = 0; switch (oper) { case '+': ret = val1 + val2; break; case '-': ret = val1 - val2; break; case '*': ret = val1 * val2; break; case '/': ret = val1 / val2; break; } return ret; } }