Custom Functions
This may be best explained by an example. Let's assume you want to
add a function "half" to divide a number by two (for demonstration
purposes).
- Create a class that extends PostfixMathCommand (in the org.nfunk.jep.function
package). In this example we will name it "Half"
- In the constructor set the number of arguments to be taken. In our
case this is one. Do this by writing "numberOfParameters = 1;"
If you want to allow any number of parameters, initialize the numberOfParameters
value to -1. It is highly recommended to study the Sum.java code as
an example of a function that accepts any number of parameters.
- Implement the run(Stack inStack) method. The parameters are passed
in a Stack object. This same stack is used as the output for the function.
So we first need to pop the parameter off the stack, calculate the
result, and finally pop the result back on the stack.
public void run(Stack inStack) throws ParseException {
// check the stack
checkStack(inStack);
// get the parameter from the stack
Object param = inStack.pop();
// check whether the argument is of the right type if (param instanceof Double) {
// calculate the result double r = ((Double)param).doubleValue() / 2;
// push the result on the inStack inStack.push(new Double(r)); } else { throw new ParseException("Invalid parameter type");
}
}
- In your main program or applet that is using the parser, add the
new function. Do this by writing
parser.addFunction("half", new Half());
Source files
|