1

Today I have a question that I had on my mind for years now.
Consider you have the following evaluation in Java:

new EvaluationListener(){  
    public boolean evaluate(boolean[] b){
        return b[0] || b[1];
    }
}

I am using this code in my program for evaluating terms of different boolean values of b[0] and b[1], but that doesn't matter at all here.
At the moment I am writing the evaluations into the source code, let the program run and watch the result in the command line.
Now I am wondering how I could implement the evaluation into command line. I would like to be able to enter an evaluation term into the command line, read it with BufferedReader etc. instead of writing it into the source code.

Is there any way to do so? I thought it would be possible by using some sort of variable aliases like $b0$. But how can I pass logical OR and AND and NOT to the program?

Thanks for your answer

6
  • 1
    I'm not sure I really understood your question, but if you want to pass the boolean values as well as the operand you could use the args at main() method. Commented Mar 21, 2014 at 11:53
  • 1
    Search for 'Java', 'Expression' and 'Evaluate' Commented Mar 21, 2014 at 12:01
  • @Caumons If I understand correctly, he is looking for some sort of Java REPL (but it's not really clear). Commented Mar 21, 2014 at 12:06
  • While reading the thread given by @Nick Holt, I am wondering if I need a parser? Commented Mar 21, 2014 at 12:09
  • Look at the javax.script API - docs.oracle.com/javase/6/docs/api/javax/script/… Commented Mar 21, 2014 at 12:16

1 Answer 1

1

Here's an example of expression evaluation with Java's script API:

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();

ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("ECMAScript");
scriptEngine.put("b1", true);
scriptEngine.put("b2", false);

System.out.println(scriptEngine.eval("b1 || b2"));
System.out.println(scriptEngine.eval("b1 && b2"));

When run, this code prints:

true
false
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this answer. It's exactely what I looked for. Can you tell me what the sign '^' does? Using it, it returns 1 instead of "true" or "false". Are there any further signs to use except '!' ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.