OO Programming with Java


1. Desktop calculator

A. Interpretation

  1. Develop a Java class for a simple calculator whose specification is given below:
package calculator;
...
Calculator calc = new Calculator();
calc.press('1');
calc.press('2');
calc.press('+');
calc.press('3');
calc.press('=');
assert calc.value()==15 : "Compute right value" ;
  1. Extends the calculator to permit the following operation:
calc = new Calculator();
calc.interpret("12+3=");
System.out.printf( "%d\n", calc.value() ); // 15

To proceed, iterate over the String and use the operations of the preceding question.

  1. Transform the program into a command line tool:
> java Calculator "12+3="
15

If no parameter is passed to the program, it passes into interactive mode and asks the user an expression to evaluate. To proceed, use a Scanner.

B. Compilation

  1. Proposes a program that transform an infix expression into a postfix one, eg. "1+2" becomes "1 2 +".
    To proceed, simply adapt the program from the preceding part to generate a new expression rather that do a computation.
  2. By using StringTokenizer and a Stack, propose a program to evaluate expressions such as "12 3 +". A value is simply pushed at the top of the stack and "+" pops the 2 values at the top of the stack and pushes the sum.

answer