评估布尔字符串表达式?
问题描述:
可能重复:
评估以字符串形式给出的数学表达式
我如何布尔值计算包含bool表达式的字符串?喜欢:
How can I boolean evaluate a string containing bool expressions? Like:
String userVar[] = {"a = 1", "b = 1", "c = 0"};
String expr = "a & b & c";
boolean result = evaluate(expr); //would evaluate to false
用户应该能够定义自己的变量( a = 1
),并定义自己的布尔表达式( a& b& c
)。所以我将所有表达式仅作为字符串。我如何评估它们?
The user should be able to define his own variables (a = 1
), and define his own boolean expression (a & b & c
). So I will have all expressions only as a string. How can I evaluate them?
答
您可以使用Nambari评论的ScriptEngine:
You can use a ScriptEngine as commented by Nambari:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
String userVar[] = {"a = 1", "b = 1", "c = 0"};
for (String s : userVar) {
engine.eval(s);
}
String expr = "a & b & c";
System.out.println(engine.eval(expr));
打印0。
另请注意表达式不是布尔表达式,而是按位运算。
Also note that the expression is not a boolean expression but a bitwise operation.