Please note, this blog entry is from a previous course. You might want to check out the current one.

Re-implement the descriptionOfProgram: method from the last lecture to display the passed program in a more user-friendly manner. Specifically …

a. It should display all single-operand operations using “function” notation. For example, 10 sqrt should display as sqrt(10).

b. It should display all multi-operand operations using “infix” notation if appropriate, else function notation. For example, 3 Enter 5 + should display as 3 + 5.

c. Any no-operand operations, like π, should appear unadorned. For example, π.

d. Variables (Required Task #1) should also appear unadorned. For example, x.

Any combination of operations, operands and variables should display properly.

Examples (E means “Enter key”) …

a. 3 E 5 E 6 E 7 + * – should display as 3 – (5 * (6 + 7)) or an even cleaner

output would be 3 – 5 * (6 + 7).

b. 3 E 5 + sqrt should display as sqrt(3 + 5).

c. 3 sqrt sqrt should display as sqrt(sqrt(3)).

d. 3 E 5 sqrt + should display as 3 + sqrt(5).

e. π r r * * should display as π * (r * r) or, even better, π * r * r.

f. a a * b b * + sqrt would be, at best, sqrt(a * a + b * b).

As you can see, you will have to use parentheses in your output to correctly display the program. For example, 3 E 5 + 6 * is not 3 + 5 * 6, it is (3 + 5) * 6. Try to keep extraneous parentheses to a minimum though (see Hints).

It might be that there are multiple things on the stack. If so, separate them by commas in the output with the top of the stack first, for example 3 E 5 E would display as “5, 3”. 3 E 5 + 6 E 7 * 9 sqrt would be “sqrt(9), 6 * 7, 3 + 5”.

Analog to the *runProgram* method we first have to check if we actually have a valid *program*. We use call *descriptionOfTopOfStack* which will work through the stack like *popOperandOffStack* already does. If after that there is something still on the stack we call *descriptionOfProgram* for the rest. To beautify the result we call *stripUnneccessaryParenthesis*.

Continue reading “Assignment #2 Task #2”