javascript - Java - ScriptEngineManager nashorn Math.random does not work -


i call follow function functionname "random" , parameter "1 , 50".

private string callfunction(string functionname, string[] parameter)             throws filenotfoundexception, scriptexception, nosuchmethodexception {          scriptenginemanager engine = new scriptenginemanager().getenginebyname("nashorn");         engine.eval(new filereader(mypath + functionname + ".js"));         invocable invocable = (invocable) engine;         object result;         if (parameter == null) {             result = invocable.invokefunction(functionname);         } else {             result = invocable.invokefunction(functionname, parameter);         }         system.out.println(result);         return (string) result;     } 

the content of random.js looks like:

  function random(min, max){     return  math.floor(math.random() * (max - min +1)) + min;   } 

the results never between 1 , 50. more 100.

if use not in java works. work math nashorn/javascript oherwise in java?

update:

my solution is:

private string callfunction(string functionname, string parameter)         throws filenotfoundexception, scriptexception, nosuchmethodexception, classcastexception {     string result = "";     engine.eval(new filereader(propertieshandler.getfulldynamicvaluepath() + functionname + ".js"));      if (parameter == null) {         result = (string) engine.eval(functionname + "();");     } else {         result = (string) engine.eval(functionname + parameter + ";");     }     return (string) result; } 

so can use parameters different types.

adding elliot's example there must wrong parameters passing in. following generates 100 values between 1 , 50.

public static void main(string[] ar) {     string script = "function random(min, max) { "             + "return math.floor(math.random() * (max - min + 1)) + min; }";     scriptengine engine = new scriptenginemanager().getenginebyname("nashorn");     invocable invocable = (invocable)engine;     try {         engine.eval(script);         (int = 0; < 100; i++) {             double result = (double)invocable.invokefunction("random", 1, 50);             system.out.println(result.intvalue());         }     } catch (scriptexception | nosuchmethodexception e) {         e.printstacktrace();     } } 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -