I\'m somehow new to Java so my question can seem trivial, however i cannot find an answer to it anywhere in my books.
I want to initiatie a dialog with a user in which h
How to convert a String into Arithmetic Expression
import bsh.*;
class Operation
{
public static void main(String[] args)throws Exception
{
Interpreter i=new Interpreter();
int r=(Integer)i.eval(args[0]);
System.out.println(r);
}
}
for this we need a separate jar file named: bsh.jar file
need to set classpath for above jar file
source: http://ohmjavaclasses.blogspot.com/2011/11/how-to-convert-string-into-arithmetic.html
You have to write an expression parser to accomplish this kind of behaviour. There are a number of ways to accomplish this:
There is no native facility in Java for evaluating strings as expressions. You must therefore do the work yourself.
If you just want a quick and dirty solution, Javassist includes a snippet compiler allowing you to define a new class with your expression, and invoke it to get your result, after which you can discard it (i.e. run it in a separate classloader). It will require some work though :)
http://www.jboss.org/javassist/
You could also look at JScheme. Need to compile & run with the jscheme jar file.
import jscheme.JS;
String query = "(+ 10 20)";
System.out.println(query + " = " + JS.eval(query));
See third example down at http://jscheme.sourceforge.net/jscheme/doc/userman.html#si
JScheme main page at http://jscheme.sourceforge.net/jscheme/main.html
It isn't so hard to parse them yourself, but if you need fast and probably accurate result, you can use one of the existing libraries to parse arithmetic expressions, like JEP or perhaps that Simple Parser for Arithmetic Expressions.
See the Jep Console for a sample. It looks like Jep is payware. It might not be a problem, otherwise as I wrote, you should be able to find a number of equivalent libraries.