Z
Z
ZadrotPro2014-03-03 00:29:16
Perl
ZadrotPro, 2014-03-03 00:29:16

How to calculate the value of a string, analogous to eval in java?

There is a string with a random expression like:
"3243-854+6-100"
How to find its value in java?
In perl it was done like this
my $vaule = eval '3243-854+6*100'; # 2295

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
cbgx74, 2014-03-03
@cbgx74

Actually answers I think from here stackoverflow.com/questions/2605032/using-eval-in-java

F
FoxInSox, 2014-03-03
@FoxInSox

JEL :

import gnu.jel.CompilationException;
import gnu.jel.CompiledExpression;
import gnu.jel.Evaluator;
import gnu.jel.Library;

public class Main {

  private static final String EVAL_VALUE = "3243-854+6-100";

  public static void main(String[] args){
    JELSample();
  }

  private static void JELSample(){

    try {
      Class[] staticLib = new Class[1];
      staticLib[0] = Class.forName("java.lang.Math");
      Library lib = new Library(staticLib, null, null, null, null);
      CompiledExpression compiledExpression = Evaluator.compile(EVAL_VALUE, lib);
      Object result = compiledExpression.evaluate(null);
      System.out.println("JEL: " + result);
    } catch (CompilationException e) {
      e.printStackTrace();
    } catch (Throwable throwable) {
      throwable.printStackTrace();
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question