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?

Recommended Answers

All 5 Replies

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.

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

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.

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.

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").

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.