最後我爲上述問題的解決方案做了代碼。
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" };
這可能有助於http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – kosa