Calculator
The aim of this example is to create a calculator for numerical
expressions. We use prefixed expressions because this kind of
expression
is easier to analyze :
- no priority
- no associativity
- the heap for computing the result is the heap of the recursive
calls.
For example, + / 4 2 1 gives the following result: 3 (= 4/2 + 1)
Moreover, the character '-' is used
as a sign by the class StreamTokenizer.
Thus, the corresponding binary operator will be represented by the word
"minus".
First version
- The interface
Operator
describes the methods necessary for an operator : get its symbol,
its arity and evaluate a well-formed expression from this
operator. .
- The class
Operators
gives certain usual operators as constants.
- The class
SyntaxErrorException
represents the exceptions due to a syntax error in an expression.
- The class
Caculator
allows to evaluate expressions, both from
the standard input or an input file. The result may be given on the
standard ouput or in an output file. This class specifically uses an
instance of java.io.StreamTokenizer
for the partition of the expressions in tokens.
Version with dynamic loading of operators
- In this version, the class
Calculator
has been cleaned, in order to separate the evaluation from the
inputs/ouputs.
- The management of the inputs/ouputs has been moved to a class
Calculators
,
which contains only class methods.
- The class Calculator has been extended into a class
CalculatorWithPlugins
,
in which the operators are loaded from a directory given as parameter
(instead of being loaded from a static array). This class specifically
uses an instance of java.lang.ClassLoader
.
- The classes
Operator
,
Operators
and SyntaxErrorException
remain unchanged.
- The classes for operators, (files .class) are
now in a directory named "
plugins
". These files are
obtained from sources
contained in a directory named "pluginsSrc
".
- The main method of this version is now in a class outside the
package calculator
:
DynamicCalculator
.
To get the result, it is necessary, with Eclipse, to :
- ask to create a project with separated sources and binaries :
- in the first dialog, click on the item create separate
source and output
folders,
- choose next,
- in the second dialog,
click on the item allow output
folders for
source folders.
- create a second source directory, for example pluginsSrc :
- use the command New from
the menu File
(menu bar or right click), then choose Source Folder,
the project under examination being selected.
- create a directory for the binaries obtained from the sources of
the directory pluginsSrc
:
- click on the directory pluginsSrc
with the right button, then select in the menu Build Path
the item Configure
Ouput Folder ... then choose Specific Ouput
Folder and enter the wanted name, for example plugins.