问题
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
回答1:
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.
回答2:
You have to write an expression parser to accomplish this kind of behaviour. There are a number of ways to accomplish this:
- Write your own expression parser using e.g. ANTLR.
- 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.
回答3:
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/
回答4:
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
回答5:
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
来源:https://stackoverflow.com/questions/962778/converting-inserted-string-to-a-compilable-expression