cnmesr
cnmesr

Reputation: 345

Cannot prevent execution of code in Java

I have written a program where you write to the console and the program will tell you if the expression is arithmetically correct. Say input is (12+1), output will be true.

Now here is a piece of code I found on the internet that will additionally calculate the solution of (12+1). However, I cannot control its execution. I only want it executes if the output is true. How can I do that? Here is what I have tried but the code is executed anyway:

Let me clarify; the if is executed although bool is false

I hope you can tell me how to fix it? Because I need this for another, longer code.

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

public class Supporter{
    public static void main(String[] args) throws ScriptException{
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        String str = "2+2";
        int counter=0;
        boolean bool=false;

        if(bool=true){
            System.out.println(engine.eval(str));
        }
    }
}

Upvotes: 0

Views: 49

Answers (1)

ajimenez
ajimenez

Reputation: 86

You have a small bug: You have to use == instead of =

if(bool == true){
    System.out.println(engine.eval(str));
}

Upvotes: 5

Related Questions