Section 3 with Remik (rz33@cornell.edu) Meeting #1Notes ******************************************************** Administrivia: Assignment #1 is out Review: RPN Calculator Stack Java syntax RPN Calculator: Why do we use stacks? ******************************************************** In 1951 a Polish mathematician wrote a book on logic. His name was Jan Lukasiewicz and he showed that rules of precedence and parentheses could be dropped by rewriting expressions. For example, 1+(2*3) can be written +1*23 (prefix notation) and also as 32*1+ (postfix or RPN) RPN means reverse Polish notation. So we can scan an RPN expression from left to right just push values onto a stack as they come, and pop them when an operator is encountered. This was actually adopted for machines to use, namely the HP calculators. RPN Java Framework: Using a Stack ************************************************************* import java.util.Stack; /** Do arithmetic RPN style. Input must look like 3 4 + 1 +. */ class RPN { Stack stack = new Stack(); /** @param string an array of elements in an RPN expression */ int eval(String[] string) { for(int i = 0; i < string.length; ++i) { if (s[i].equals("+")) { // do addition and push the result int a = ((Integer)stack.pop()).intValue(); int b = ((Integer)stack.pop()).intValue(); stack.push( new Integer(a + b)); } else { // must be a number stack.push( new Integer(s[i])); } } return ((Integer)stack.pop()).intValue(); } }