0
int a = 4, b = 3;
String code = "a*b+a+2*b";
int result = unknown_function(code);
System.out.println(result);//expecting 22

Any ideas how to do that please?

5
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by masijade
0
int a = 4, b = 3;
String code = "a*b+a+2*b";
int result = unknown_function(code);
System.out.println(result);//expecting 22

Any ideas how to do that please?

if you can post ur full code it will help better.

0

o.O its all code, Sir.
I want to know how to convert String into a code which can be evaluated. Like it is eval() in PHP

0

You can use a special class in string called StringTokenizer.

Using this you can delimit the operators such as + * etc and jus get the variables alone.

Then depeding upon the sequence given u can then program.

0

The StringTokenizer class documentation says its use is discouraged in new code and to use String class's split method instead.

And you cannot cause a String to be evaluated as if it was a piece of programmer written code. Instead, you could use if statements, for example "if a + is seen, then call method X" etc.

0

Java does not have an Eval. You would have to either parse it and perform actions logically, or you would have to create a class "on the fly", either with BCEL (Google that) or by generating and then compiling code, or you can look into the scripting engine support in 1.6 (I.E. Google "Rhino").

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.