Java does not have an eval()
statement that can take a string of code and compile and interpret it within a program. You could, using Java, write such a command (you have access to the java parser, can write your own classloader, ...), but why bother whenyou already have built-in scripting support in the language.
The usual way to interpret expressions is to write a parser for your expression language and interpret the resulting parse tree (if you do not understand words like "parser" and "parse tree" this is not the easiest route for you). When done correctly, this is the fastest approach.
However, you can also rely on the built-in scripting support:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class T {
public static String interpret(String js) {
try {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
return engine.eval(js).toString();
} catch (ScriptException e) {
// Shouldn't happen unless somebody breaks the script
throw new RuntimeException(e);
}
}
public static void main(String args[]) {
String str=args[0];
str = str.replaceAll("1", "true");
str = str.replaceAll("0", "false");
str = str.replaceAll(" [&] ", "&&");
str = str.replaceAll(" [|] ", "||");
System.out.println(interpret(str));
}
}
Notice that this is somewhat slow and generally considered cheating if the exercise expected you to use a parser. Additionally, since JS is a full-fledged language, it is a lot less safe than having a custom-built, restricted parser: you have to go to great lengths to sanitize the JS to prevent people from entering "evil expressions" that can tie up your system or do other nasty stuff.
The output is, for
javac T.java && java T "(0 & (0 || 1))"
(notice that the first argument to the program is the expression to parse)
false