0
String str = "2 > 1";
Boolean result;

How could I convert the string to a boolean expression, and then evaluate it?

  • I don't think any of the answers in the "duplicate" question is what you want. If that's the case, ... for your example of simple boolean expression (e.g., pattern "[number] [comparison operator] [number]"), (1) Split() the string into three parts (using spaces as a separator), (2) ParseInt() the first and third parts, (3) Just switch or If/else if all possible operators (e.g., ">", "=", ">=", etc.), and, in each block, compute the result based on the second part (just a string) (4) The resulting boolean value is your answer. – realharry Nov 21 '17 at 00:44
  • @realharry *or*, `Boolean result = (Boolean) new ScriptEngineManager().getEngineByName("nashorn").eval(str);` (which, basically, is the top answer in the duplicate). – Elliott Frisch Nov 21 '17 at 00:51
  • 1
    @ElliottFrisch that's my point. the OP probably didn't want that kind of solution. I'll let him speak for himself, but it was a simple question, which I thought called for a simple answer (in terms of "how to program", not how to use JDK apis). – realharry Nov 21 '17 at 00:54

0 Answers0