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

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
Brian
  • 1,318
  • 1
  • 16
  • 33
  • 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. – Caumons Mar 21 '14 at 11:53
  • 1
    Search for 'Java', 'Expression' and 'Evaluate' – Nick Holt Mar 21 '14 at 12:01
  • @Caumons If I understand correctly, he is looking for some sort of Java REPL (but it's not really clear). – Florent Bayle Mar 21 '14 at 12:06
  • While reading the thread given by @Nick Holt, I am wondering if I need a parser? – Brian Mar 21 '14 at 12:09
  • Look at the `javax.script` API - http://docs.oracle.com/javase/6/docs/api/javax/script/package-summary.html – Nick Holt Mar 21 '14 at 12:16
  • If the actual process of evaluating expressions is of any interest, then check GNU coreutils expr.c source code (I ported it to Java once for fun): http://git.savannah.gnu.org/gitweb/?p=coreutils.git;a=blob_plain;f=src/expr.c;hb=HEAD – Torben Mar 21 '14 at 12:18

1 Answers1

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
Nick Holt
  • 33,455
  • 4
  • 52
  • 58
  • 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 '!' ? – Brian Mar 21 '14 at 19:40