views:

295

answers:

4

Hi, 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 he would enter an arithmetic expression (ex. (2*x+y)) And then print out the result for such expression (for given values of x and y)

    String EXPRESION = null;
 EXPRESION = JOptionPane.showInputDialog("Please enter expresion for dy/dx");
 double x = 1.4;
 double y = 5;
 double output = HERE IS THE PROBLEM
 JOptionPane.showMessageDialog("The value is" +output);

I fail to convert the string inserted by the user so it would serve as an arithmetic expression for x and y and hence define the value for output

TIA JMT

+2  A: 

You have to write an expression parser to accomplish this kind of behaviour. There are a number of ways to accomplish this:

  1. Write your own expression parser using e.g. ANTLR.
  2. Include a scripting language (Jython, Beanshell, JavaScript...) and use that to parse and evaluate the expressions. The Java Scripting API can show you how to do this.
Bruno Ranschaert
+3  A: 

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.

PhiLho
+1  A: 

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/

Thorbjørn Ravn Andersen
A: 

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

xagyg