how to convert a string into a conditional express

2019-06-05 08:58发布

问题:

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.

Thank You in advance!

回答1:

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!