2016-02-28 30 views
0

我使用functionName「random」和參數「1和50」調用跟隨函數。Java - ScriptEngineManager nashorn Math.random不起作用

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; 
    } 

random.js的內容是這樣的:

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

的結果是從來沒有1到50之間總是超過100

如果我在java中不使用它有用。 在java中從nashorn/javascript oherwise工作數學?

UPDATE

我的解決辦法是:

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; 
} 

所以我可以使用不同類型的參數。

回答

0

添加到艾略特的例子,必須有什麼問題要傳遞的參數之間的100個隨機值。下面還1和50

之間產生100個值
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); 
     for (int i = 0; i < 100; i++) { 
      Double result = (Double)invocable.invokeFunction("random", 1, 50); 
      System.out.println(result.intValue()); 
     } 
    } catch (ScriptException | NoSuchMethodException e) { 
     e.printStackTrace(); 
    } 
} 
+0

是的,你有權利!我一直使用字符串參數!我認爲invokeFunction只能使用字符串。謝謝!!! – mscholz3

1

我調整了一下你的例子,你不能指定ScriptEngineScriptEngineManager,它不清楚你如何顯示你的隨機值,或者你如何調用random。然而,這產生150這裏

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"); 
    try { 
     engine.eval(script); 
     for (int i = 0; i < 100; i++) { 
      engine.eval("print(random(1, 50));"); 
     } 
    } catch (ScriptException e) { 
     e.printStackTrace(); 
    } 
} 
+0

感謝您的回覆!使用invokeFunction不起作用,但用你的解決方案它就像一個魅力!將ScriptEngine分配給ScriptEngineManager是該帖子的輸入錯誤。我的程序的用戶可以使用他自己的JavaScript,這就是爲什麼我隨機嘗試它。 – mscholz3

+0

我需要4個國旗帖子才能投票發佈;) – mscholz3