Link to home
Start Free TrialLog in
Avatar of musicc
musicc

asked on

String Conversion

Is there an easy way to covert String let’s say “x + y”? So that, I could use it as an equation. For example,

text.getText(); // x + y
z = x + y;

Assume that I have declared x and y.

Thank you
Avatar of JakobA
JakobA

No.

Java is a compiled language, and once a program have been compiled it cannot easily understand such 'human readable' expressions.

In scripting languages like Basic, Perl, PHP and JavaScript it can be done easily as those languages are not compiled, instead they are run by being incrementally compiled and executed. The compiler is always present and it is no trouble to have it interpret and execute the string "x + y".

That does not mean it is impossible to write a java program to read and interpret a string like "x + y", it is a stock project for first or second year computing classes.

But not exactly easy (last time I made such a program it ran to about 200 lines of code).

regards JakobA
There are interpretters that will do exactly what your looking for.

One is called Bean Shell for Java:
http://www.beanshell.org/

I've also developed one that I am selling.  First you define your variables and functions in a set of libraries, then you can run the expressions as a string as you are suggesting.
Avatar of musicc

ASKER

I found one. It is very useful.
Here is the site.
http://www.singularsys.com/jep/doc/html/index.html
JakobA gave him the answer, and I gave him the best work around, I believe the points should be split.
Not for me please.
ASKER CERTIFIED SOLUTION
Avatar of modulo
modulo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial