Calculator: console
The Calculator Sample
This sample consists of a command line reverse Polish notation (RPN) calculator.
Compiling
To compile the example:
- Launch EiffelStudio.
- Click Add project
- Browse to $ISE_EIFFEL\examples\base\calculator\
- Choose calculator.ecf
- Change the target from classic to dotnet
- Choose the location where the project will be compiled, by default the same directory containing the configuration file.
- Click Open.
Running
After you launch the sample, the following text appears in a console:********************************* Calculator in reverse Polish form ********************************* Allowable operations are: '/': Divide top two numbers on the stack. '0': Empty the stack. 'a': Enter operand onto stack. '?': Help. '*': Multiply top two numbers on the stack. '+': Add top two numbers on the stack 'q': Quit. '-': Subtract top two numbers on the stack. Enter a number, followed by :
Enter the first number to be put onto the stack, for example 3
.
You may then add another number on the stack by entering the character "a
": ********************************* Calculator in reverse Polish form ********************************* Allowable operations are: '/': Divide top two numbers on the stack. '0': Empty the stack. 'a': Enter operand onto stack. '?': Help. '*': Multiply top two numbers on the stack. '+': Add top two numbers on the stack 'q': Quit. '-': Subtract top two numbers on the stack. Enter a number, followed by : 3 Accumulator = 3 Next operation? a Enter a number, followed by :
Enter a second number, for example 2
. You can then apply any operation to the two operands such as minus: ... Next operation? a Enter a number, followed by : 2 Accumulator = 2 Next operation? - Accumulator = 1 Next operation?
You may use the operation 0
to clear the stack at any time. You may use q
to quit the program.
Under the Hood
This sample shows how to leverage EiffelBase data structures in a simple Eiffel system. The root class CALCULATOR
first instantiates all state objects, each corresponding to one possible operation. The state classes all inherit from STATE
. They are:
-
PLUS
: Add stack's two top numbers. -
MINUS
: Substract stack's two top numbers. -
MULTIPLY
: Multiply stack's two top numbers. -
DIVIDE
: Divide stack's two top numbers. -
EMPTY
: Empty stack. -
HELP
: Prints available commands. -
QUESTION
: Get number from user. -
QUIT
: Close application.
Each of these classes implement the feature do_one_state
from STATE
which performs the operation associated with the state.The initial state is QUESTION
which asks for the initial number to put in the accumulator. Following states depend on the user input.Every descendant of STATE
implement the feature operation
which performs the corresponding stack transformation.