0

I’m really stuck on this problem.

I have several different Strings with different values and lengths like “true & true“ or “(!true & false) | true“.

Now I have to check if these statements are logically true or not. My idea was that I could somehow parse them to a boolean object and check them in an if statement.

For example:

     String a = “(true & false) | true“;

     if(a == true){

        System.out.println(“the equation is true“);

     }else{

        System.out.println(“the equation is false“);
     }

I already tried methods like Boolean.parseBoolean(String) or Boolean.valueOf(String).

Is there any way to do this? Or any other approach how I can solve this problem?

I appreciate the help. Thanks a lot.

  • I don't think there is a prebuilt solution for this problem (though I'd love to be proven wrong). In theory you would have to parse the string to extract the different logical "tokens" (e.g. `true`, `false`, `&`, ...) and build an AST from this. – jBuchholz Nov 04 '21 at 08:03
  • You should first split the String to get the last word, using the following expression: String a = "(true & false) | true".trim(); String lastWord = a.substring(a.lastIndexOf(" ")+1); After of this, you'll be able to use parseBoolean or valueOf as you tried previously – Marco Nov 04 '21 at 08:37

2 Answers2

0

You should consider using a stack approach for evaluating the expression. Consider that you have the operators, (, ), !, &, | and only 2 operands "true" and "false"

  1. Give priority to your operators first
  2. Make a postfix expression out of this infix one. (You can get the help from https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/.)
  3. Process the postfix expression using a stack. (Keep pushing until you encounter an operator, pop last 2 elements from stack and perform the operation and push back to the stack. and continue until the end of the expression.
abstractnature
  • 456
  • 2
  • 9
0

May be you can use spel which we used in rule engine in our team.

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 04 '21 at 08:24