1

I have a String "a>b" and I want to convert into a normal conditional expression. How to do this in Android means using only JSE.

String abc = "a>10";
if(abc){
 // TO SOME TASK
}

Any help will be appreciated.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
AndroidDev
  • 888
  • 3
  • 13
  • 27
  • 4
    http://stackoverflow.com/questions/2605032/using-eval-in-java – Zutty Mar 14 '13 at 09:48
  • 1
    but javax.script.ScriptEngine and javax.script.ScriptEngineManager are not available in android. – AndroidDev Mar 14 '13 at 10:14
  • You can take a look at Parboiled to parse simple boolean expressions. – Alex Mar 14 '13 at 12:44
  • I don't think there is any need to bring JSE into the picture. I would just use regex to get the index of the special conditional character. Then use String[] parts = abc.split(specialChar) and write conditional code like if(specialChar=='>'){doSomething with parts[0] and parts[1].} – Avik Mar 29 '13 at 12:31
  • Write a parser. Can't get around needing to write one. – Patashu May 06 '13 at 03:23
  • 3
    Does this answer your question? [Evaluate String as a condition Java](https://stackoverflow.com/questions/10917878/evaluate-string-as-a-condition-java) – helvete Sep 04 '20 at 13:52

2 Answers2

2

I would recommend using a "helper" method that returns a boolean result, so the statement would look something like this

String abc = "a>10";

if(stringToConditional("a>b"))
{
  //TO SOME TASK
}

private boolean stringToConditional(String str)
{
  //code here
}

From there, the "helper" method can split the string into three parts using regex. A helpful, abet dense, tutorial can be found here. From there, a and b can be parsed using JSE methods. It looks something like this:

String a = "1.21";
double a1 = Double.parseDouble(a); //a1 is now equal to 1.21

From there, the next step would be to compare the conditional string (">", "<=", "==", etc.) to a list of known operators, and then testing the operation and returning the result as the method's boolean return. For example:

String operator = ">=";
if (operator.equals(">="))
{
  return a1>=b1;
}
...

Hopefully I wasn't too unclear or off the mark. I'd be happy to elaborate, clarify or simplify. Good Luck!

WilBur
  • 270
  • 4
  • 9
0

In Java we can use javaScriptEngine API:

String condExptn="34>5&&78<90";
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
result = engine.eval(condExptn.toString().trim());
xKobalt
  • 1,498
  • 2
  • 13
  • 19