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
fasseg
source share