Evaluate boolean values ​​in Java

I am trying to evaluate the following from a line

boolean value = evaluate("false || true && true && false || true"); 

I need to get a boolean true for this.
Any ideas on how to solve this problem in the most efficient way?

+6
java eval
source share
4 answers
 String value = ("false || true && true && false || true"); boolean result = false; for (String conj : value.split("\\|\\|")) { boolean b = true; for (String litteral : conj.split("&&")) b &= Boolean.parseBoolean(litteral.trim()); result |= b; } System.out.println(result); // prints true 
+7
source share

If the only operators are && and || I think this will work:

  static boolean eval(String str) { String s = str.replaceAll("\\s|\\|\\|false|false\\|\\|", ""); return !s.contains("false") || s.contains("||true"); } 

For more complex expressions, I found this library just for this. I don’t know how effective it is.

+1
source share

You will need a little grammar of boolean expressions. Recursive parsing should do the trick.

If you do not know how to write such a parser, you can use JavaCC or something like that.

0
source share

There are parser generators for which you can define a grammar.

But if you only got || and && as operators and true and false values, you can easily do it yourself by implementing a very simple state machine:

1.) Divide the string into tokens

2.) parse the largest value on the left using Boolean.parseBoolean (token) and store its value in some instance variable (your state)

3.) combine your instance variable with the following logical token using this operator

4.) Repeat step3 until you finish the whole line

This seems to work, although I'm not sure he tested it :)

 public class BooleanFSParser { private boolean parse(String data) { String[] tokens=data.split("\\s"); boolean state=Boolean.parseBoolean(tokens[0]); for (int i=1;i<(tokens.length / 2) + 1;i=i+2){ if (tokens[i].equals("&&")){ state=state && Boolean.parseBoolean(tokens[i+1]); }else{ state=state || Boolean.parseBoolean(tokens[i+1]); } } return state; } public static void main(String[] args) { BooleanFSParser parser = new BooleanFSParser(); boolean val = parser.parse("true && true || false"); System.out.println(String.valueOf(val)); } } 

thats should give you a correctly parsed value, but it will be a bit more complicated if, for example, you allow parentheses;)

have fun and check out Finite-state_machine theory here

0
source share

All Articles