我如何布尔值计算包含bool表达式的字符串?像:
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
)。所以我将所有表达式仅作为字符串。我该如何评估它们?
答案 0 :(得分:3)
您可以使用Nambari评论的ScriptEngine:
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。
另请注意,表达式不是布尔表达式,而是按位运算。
答案 1 :(得分:1)
最后,我为上述问题的解决方案制作了代码。
public static void main(String[] args) {
String userVar[] = { "a = 1", "b = 0", "c = 1" };
String expr = "a & b & c";
// System.out.println(Boolean.valueOf("true"));
Map<String, Boolean> booleanMap = getBooleanMap(userVar);
// System.out.println(booleanMap);
boolean evaluate = evaluate(booleanMap, expr);
System.out.println("Final Result = " + evaluate);
}
public static boolean evaluate(Map<String, Boolean> operVal, String eq) {
String[] split = eq.split(" ");
boolean orgVal = false;
boolean prevVal = false;
boolean firstTime = true;
String lastOpr = "&";
for (String exp : split) {
// System.out.println(orgVal + " " + exp);
// System.out.println(exp);
if (exp.equals("&")) {
lastOpr = "&";
orgVal = orgVal && prevVal;
} else if (exp.equals("|")) {
lastOpr = "|";
orgVal = orgVal || prevVal;
} else {
prevVal = operVal.get(exp);
if (firstTime) {
orgVal = prevVal;
firstTime = false;
}
}
}
if (lastOpr.equals("&")) {
lastOpr = "&";
orgVal = orgVal && prevVal;
} else if (lastOpr.equals("|")) {
lastOpr = "|";
orgVal = orgVal || prevVal;
}
// System.out.println(orgVal);
return orgVal;
}
public static Map<String, Boolean> getBooleanMap(String[] val) {
Map<String, Boolean> result = new HashMap<String, Boolean>();
for (String exp : val) {
String[] split = exp.split("=");
// System.out.println(split[0].trim());
// System.out.println(split[1].trim());
String opr = split[0].trim();
int intVal = Integer.valueOf(split[1].trim());
boolean boolVal = false;
if (intVal == 1) {
boolVal = true;
}
result.put(opr, boolVal);
}
return result;
}
测试用例 - 1
String userVar[] = {"a = 1", "b = 1", "c = 0"};
测试用例 - 2
String userVar[] = { "a = 1", "b = 1", "c = 1" };