使用beanshell通过将变量传递给Math.pow()来评估java中表达式的值

时间:2016-01-16 01:36:32

标签: java beanshell

我试图直接在java中评估一个表达式,虽然这是一个简单的表达式,但使用beanshell对我来说似乎很难

无论如何,这是我的问题:

我可以通过在java中使用

直接评估指数值
double c = Math.pow(2,3);

或其他方式

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

在Beanshell中,我正在尝试做同样的事情,它有效:

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

但这些行不起作用:

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

**this is my progress **

更新:我的代码显示错误消息 源文件:内联评估:``Math.pow(finalStr,2);'':未定义的参数:

1 个答案:

答案 0 :(得分:2)

BeanShell脚本无权访问Java本地变量。该脚本只能使用任何set()方法查看已赋予BeanShell enter image description here的值:

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

Interpreter甚至有这方面的例子。