evaluate boolean values in Java

醉酒当歌 提交于 2021-02-07 13:38:40

问题


I am trying to evaluate the following from a string

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

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


回答1:


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



回答2:


If the only operators are && and ||, then 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 complicated expressions, I found this library just for that. Don't know how efficient it is though.




回答3:


You'll need a small boolean expressions grammar. A bit of recursive parsing should do the trick.

If you don't know how to write such a parser, you may use JavaCC or something similar.




回答4:


there are parsergenerators available for which you can define a grammar.

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

1.) Split the string into the tokens

2.) parse the left most value by using Boolean.parseBoolean(token) and safe it's value in some instance variable (your state)

3.) combine your instance variable with the next boolean token using the given operator

4.) Repeat step3 until you finished through the whole string

This seems to work although i havent thorougly 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 cirrectly parsed value, but it will get a bit more complex if you allow brackets for example ;)

have fun and check here for the theory Finite-state_machine



来源:https://stackoverflow.com/questions/2974402/evaluate-boolean-values-in-java

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