Table of contents:

Customizing built-in evaluator

Restricting an evaluator

Javaluator come with some built-in functions or operators. But, for some uses, it could be too much.

Imagine you are developping a simple calculator to learn basic operations to children. For sure, the built-in trigonometric functions are not valuable. The good news is that Javaluator allows you to customize built-in evaluator to recognize only a subset of the built-in functions, operators, constants, or brackets.

This could be done by passing a parameters argument to the built-in constructor.

First, you have to create a Parameters instance, then add the functions, operators, constants and brackets you want to it.

Parameters params = new Parameters();
// Define the parameters.

Then create the evaluator, it will only know what is defined in its parameters.

DoubleEvaluator evaluator = new DoubleEvaluator(params);

Here is a complete working sample code:

package com.fathzer.soft.javaluator.examples;
import com.fathzer.soft.javaluator.*;
/** An example of how to restrict operators, functions and constants of an existing evaluator.
public class Restricting {
  public static void main(String[] args) {
    // Let's create a double evaluator that only support +,-,*,and / operators, with no constants,
    // and no functions. The default parenthesis will be allowed
    // First create empty evaluator parameters
    Parameters params = new Parameters();
    // Add the supported operators to these parameters
    // Add the default expression brackets
    // Create the restricted evaluator
    DoubleEvaluator evaluator = new DoubleEvaluator(params);
    // Let's try some expressions
    doIt(evaluator, "(3*-4)+2");
    doIt(evaluator, "3^2");
    doIt(evaluator, "ln(5)");
  private static void doIt(DoubleEvaluator evaluator, String expression) {
    try {
      System.out.println (expression+" = "+evaluator.evaluate(expression));
    } catch (IllegalArgumentException e) {
      System.out.println (expression+" is an invalid expression");

The output is (3*-4)+2 = -10.0
3^2 is an invalid expression
ln(5) is an invalid expression


Back to top