Make a formula from a String into a number

I’m currently trying to make a problem to calculate a Expression in a String. Until now I used a code like this:

final ScriptEngine js=new ScriptEngineManager().getEngineByName("js");
String eq="5*(2+1)";
try{
	double eg=(((Double) js.eval(eq)).doubleValue());
	println(eg);
	}
	catch(ScriptException c){
	throw new RuntimeException(c);
	}

But is there another way to do this that doesn’t involve using a js interpreter?

1 Like

as far as i know eval is evil. this page will give you all the lingo you need to research how to evaluate expressions

1 Like
2 Likes

If your use case is things like "5*(2+1)" then the Jasmine library by @quark – that @GoToLoop linked to above – is definitely the way to go. It is expressive and blazing-fast.

This sketch shows how to use Jasmine to calculate 5*(2+1) and also how you can evaluate the expression a*(b+c) for different values.

import org.quark.jasmine.*;

String strExpr = "5*(2+1)";
Expression expr = Compile.expression(strExpr, false);
int v = expr.eval().answer().toInteger();
println(v);

// Can also create a general solution to a * ( b + c)
strExpr ="a * (b + c)";
expr = Compile.expression(strExpr, false);
v = expr.eval(5, 2, 1).answer().toInteger();
println(v);
// Now solve 16 * (10 - 5)
v = expr.eval(16, 10, -5).answer().toInteger();
println(v);

should be enough to get you started.

2 Likes

I have no idea whether the OP made use of Jasmine but this discussion made me revisit the library and play with Java bytecode again.

So I have updated the library with new examples (only two before :innocent:) and added some new methods to those recognised by Jasmine.

Anyway you should be able to install Jasmine 1.1 through the Contributions Manager in a couple of days.

5 Likes

Yes in the end I made use of it! I’m exited to see the other features the library has to offer!