Search code examples
javabeanshell

evaluate the value of a expression in java using beanshell by passing variable to Math.pow( )


i was trying to evaluate a expression in java directly, though it is a easy expression , it seems difficult to me by using beanshell

anyway , this is my problem:

i can directly evaluate a value of exponential by using in java

double c = Math.pow(2,3);

or another way

int a=2,b=3;
double c = Math.pow(a,b);

In Beanshell i am trying to do the same , it works:

import bsh.Interpreter;
Interpreter interpreter = new Interpreter();
int a1=2, b1=3;
String equation = "Math.pow(2,3)";
Object checkIt = interpreter.eval(equation);
System.out.println(checkIt.toString);

but these lines dont work:

String equation = "Math.pow(a1,b1)";
Object checkIt = interpreter.eval(equation);
System.out.println(checkIt.toString);

**this is my progress**

update : my code shows me the error message Sourced file: inline evaluation of: ``Math.pow(finalStr,2);'' : Undefined argument:


Solution

  • The BeanShell script does not have access to Java local variables. The script can only see values that have been given to the BeanShell Interpreter using any of the set() methods:

    import bsh.Interpreter;
    Interpreter interpreter = new Interpreter();
    interpreter.set("a1", 2);
    interpreter.set("b1", 3);
    String equation = "Math.pow(a1,b1)";
    Object checkIt = interpreter.eval(equation);
    System.out.println(checkIt);
    

    The javadoc even has examples of this.