Javlon3002
Javlon3002

Reputation: 3

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

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?

Upvotes: 0

Views: 122

Answers (1)

yuri777
yuri777

Reputation: 377

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);
    
    }
}

Update. Previous code works for Java versions from 8 to 14. For new versions you can add next dependencies:

<dependency>
    <groupId>org.graalvm.js</groupId>
    <artifactId>js-scriptengine</artifactId>
    <version>22.1.0</version>
</dependency>
<dependency>
    <groupId>org.graalvm.js</groupId>
    <artifactId>js</artifactId>
    <version>22.1.0</version>
</dependency>

and change code:

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

Upvotes: 1

Related Questions