评估布尔字符串表达式? [英] Evaluate boolean string expressions?

查看:89
本文介绍了评估布尔字符串表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

评估以字符串形式给出的数学表达式

我如何布尔值计算包含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.

这篇关于评估布尔字符串表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆