Calculator
The goal of this example is to realize a calculator for numerical
expressions. We use prefixed expression 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 has for 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
describe the methods necessaries for an operator : get its symbol,
its arity and evaluate an well-formed expression from this
operator. .
- The class Operators gives as constants some usuals operators.
- 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 uses in particular 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 have been moved to a class Calculators, which contains only classes methods.
- The class Calculator has been extended into a class CalculatorWithPlugins,
in which the operators are loading from a directory given as parameter
(instead being loaded from a static array). This class uses in
particular an instance of java.lang.ClassLoader.
- The classes Operator, Operators and SyntaxErrorException remain inchanged.
- The classes for operators, (files .class) are now in a directory "plugins". These files are obtained from sources contained in a directory "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 the item create separate source and output
folders,
- choose next,
- in the second dialog, click 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 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.