Home > database >  How to change the String containing zero and one to boolean function in Java?
How to change the String containing zero and one to boolean function in Java?

Time:05-05

I have a string that is a boolean function. I want to calculate its value in boolean. Is there any function to do that in Java?

I have string line str = "0 1 !(0 1 1) 1*0 !1";

I want this: boolean result = false || true || !(false || true || true) || true && false || !true;

I did it for the strings whose length is 4 elements by using conditions but I have to apply this to a String that consists of more than 20 elements.

It is impossible to calculate all of the combinations. What do you think I should do?

CodePudding user response:

You can use ScriptEngine:

import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.ScriptEngine;

public class Main {

    public static void main(String[] args) throws ScriptException {

        ScriptEngineManager manager=new ScriptEngineManager();
        ScriptEngine engine=manager.getEngineByName("js");

        String in="0 1 !(0 1 1) 1*0 !1";
        in=in.replaceAll("0", "false");
        in=in.replaceAll("1", "true");
        in=in.replaceAll("\\ ", "||");
        in=in.replaceAll("\\*", "&&");
        //System.out.println(in);

        Boolean result = Boolean.valueOf(engine.eval(in).toString());
        System.out.println(result);
    
    }
}
  • Related