CalcPro is a colourful, math-inclined single-file Java demo that implements the Interpreter Design Pattern to parse and evaluate custom formulas like
ADD(5, 10),MULTIPLY(ADD(2,3),4)andDIVIDE(SUBTRACT(20,4),2). It also supports variables via aContext(e.g.,x = 5).
- Clean AST-based interpreter: each operation is an
Expressionimplementation (Add, Subtract, Multiply, Divide, …). - Operator registry — register new operators (e.g.,
POWER) without touching parser code. - Interactive Swing GUI: colourful header, math doodles, variables panel and instant evaluation.
- Simple, single-file implementation ideal for learning, prototyping, or extending.
GitHub: https://github.com/Tharindu714/CalcPro-Custom-Formula-Interpreter
ADD(5, 10)→15.0MULTIPLY(ADD(2, 3), 4)→20.0DIVIDE(SUBTRACT(20, 4), 2)→8.0MULTIPLY(ADD(x, 3), 2)withx = 5→16.0
- Ensure you have Java (JDK 8+) installed.
- Clone the repo:
git clone https://github.com/Tharindu714/CalcPro-Custom-Formula-Interpreter.git
cd CalcPro-Custom-Formula-Interpreter- Compile & run the single Java file (it's included at the root):
javac CalcPro_Interpreter_GUI.java
java CalcPro_Interpreter_GUIThe app prints demo outputs to the console and opens the colourful CalcPro GUI.
- Expression (interface) — exposes
double interpret(Context ctx). - Terminal expressions —
NumberExpression,VariableExpression. - Non-terminal (composite/binary) —
BinaryExpression(left/right) with subclassesAddExpression,SubtractExpression,MultiplyExpression,DivideExpression,PowerExpression. - Context — holds variable name/value map and resolves variables at runtime.
- FormulaParser — parses strings into an AST, handles nested function calls and top-level comma splitting.
- OperatorRegistry — maps operation names (
ADD,POWER) to small factory lambdas that buildExpressionobjects.
This separation keeps the parser stable while new functionality is added by registering new expression creators.
- Create the expression (already present in code as
PowerExpression):
class PowerExpression extends BinaryExpression {
public PowerExpression(Expression left, Expression right) { super(left, right); }
@Override
public double interpret(Context ctx) throws Exception {
return Math.pow(left.interpret(ctx), right.interpret(ctx));
}
}- Register it in
OperatorRegistry(one line):
OperatorRegistry.register("POWER", args -> {
requireArgCount("POWER", args, 2);
return new PowerExpression(args.get(0), args.get(1));
});No parser changes required — just class + registry entry.
Contributions welcome — fork the repo, add operators, file issues, or submit PRs. If you add interesting operators (TRIG, LOG, SUM over lists), please include tests and example formulas.
MIT — feel free to reuse and adapt.
Created with ❤️ for learners and tinkers — Tharindu's CalcPro demo.

