Courses‎ > ‎APCS - Term 1‎ > ‎Konstantinovich‎ > ‎

2019-03-25 Calculator

posted Mar 25, 2019, 6:05 AM by Konstantinovich Samuel   [ updated Mar 25, 2019, 7:04 AM ]
What is/isn't on the AP:

Quick Reference: (1st page only!)


GOAL: Evaluate a post fix expression

Evaluate an arbitrary postfix expression. Assume all results are doubles (do not have to preserve int when you run an operation on two ints)

valid numbers:
any int or double.

valid operators: all operators are binary (they work on 2 values) so you cannot have (1 2 3 +) this would require parenthesis.
Add, subtract, multiply, divide, remainder (Use the corresponding java operations)
 +
 -
 *
 /
 %
Treat all division as floating point, e.g.   "1 2 /"   is 0.5

All values and operators are separated by a single space:
"10 2.0 +"
"11 3 - 4 + 2.5 *"
"8 2 + 99 9 - * 2 + 9 -"
"1 2 3 4 5 + * - -"



Discussion!
1. How can we write an algorithm to evaluate any postfix expression?
2. Can you do it in a single pass reading from left to right?



Write the eval(String) method, that will correctly evaluate a post-fix expression.
eval("10 2.0 +") is 12.0
eval("11 3 - 4 + 2.5 *") is 30.0
eval("8 2 + 99 9 - * 2 + 9 -") is 893.0
eval("1 2 3 4 5 + * - -") is 26.0
The order is left to right just like scheme : "3 2 -" is 1




LAB
public class Calculator{
    /*Evaluate a postfix expression stored in s.
     *Assume valid postfix notation, separated by spaces.
     */
    public static double eval(String s){}
}


suggestions:
1. Convert your string into tokens. (A list of values and operators)
1b. Test this by printing each one!
2. Instead of printing each one, decide what to do with them...

Comments