Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

evaluate boolean values in Java

Tags:

java

eval

I am trying to evaluate the following from a string

boolean value = evaluate("false || true && true && false || true");

I need to get a boolean value of true for this one.
Any ideas on how to solve this problem in the most efficient way?

like image 286
Adnan Avatar asked Jun 04 '10 13:06

Adnan


2 Answers

String value = ("false || true && true && false || true");
boolean result = false;
for (String conj : value.split("\\|\\|")) {
    boolean b = true;
    for (String litteral : conj.split("&&"))
        b &= Boolean.parseBoolean(litteral.trim());
    result |= b;
}
System.out.println(result); // prints true
like image 75
aioobe Avatar answered Sep 18 '22 01:09

aioobe


If the only operators are && and ||, then I think this will work:

  static boolean eval(String str) {
    String s = str.replaceAll("\\s|\\|\\|false|false\\|\\|", "");
    return !s.contains("false") || s.contains("||true");
  }

For more complicated expressions, I found this library just for that. Don't know how efficient it is though.

like image 40
JRL Avatar answered Sep 22 '22 01:09

JRL