Hy I’m trying to bypass the process of making an arithmetical expression parser, cuz it’s a bit hart to build it from scratch and neither do i have the knowledge of writing one and we aren’t allowed to use other material for it.I came up with the idea of making a class that writes the code to an other class file thus bypassing the string-to-expression evaluation process.
public void PrintCode(String filename,String a) {
PrintStream ps = null;
try {
ps = new PrintStream(filename);
} catch (FileNotFoundException ex) {
System.out.println("printWords: File open error: " + filename);
}
ps.println(i);
ps.println(" public int a = "+a + ";\n\n" + " public int geta()\n {\n return a;\n }" +"\n\n}");
ps.close();
}
a is the given expression in String.The filename is for ex.: expression.java.
The other curious thing is that java can calculate these expressions in code , but there is no built-in function to evaluate given string type expressions.My problem is in fact that this code writing is saved after the program is finished and I need to reload the class after writing, or just load it after writing and then execute the geta() method to do the calculation.
The other thing is to restart the program from code somehow and continue from that point.
I am just a rookie to this we learned java for this semester only.. so if something is very wrong here , I apologize.And thanks in advance for any help!
EDIT: We didn’t learn about javascript so we can’t , or aren’t allowed to use it…sorry.
You can write bytecode from Java by using some of the libraries out there like ASM, but my suggestion is to use the ScriptEngine (Java 6+) interface to use JavaScript or some other sccripting language to execute your maths.
I will update my blog with a post on this because I’m going to use it on a project of my own. I will comment back when the post will be available.