how to convert a string into a conditional expression in java (Android)?

Deadly 提交于 2019-12-08 06:45:13

问题


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!



来源:https://stackoverflow.com/questions/15405809/how-to-convert-a-string-into-a-conditional-expression-in-java-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!