-3

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.

  • If you generate code for evaluating expressions, how will you handle errors in the expression? Generated code will not even compile. – Shyamal Pandya Dec 14 '12 at 15:30
  • I don't really need error handling, it's a small project , but if it can't be done I'll quit if I have no other option as I said before. – Aron Molnar Dec 14 '12 at 15:35
  • Would something like this help?: http://stackoverflow.com/questions/2902458/is-it-possible-to-pass-arithmetic-operators-to-a-method-in-java – jtyler Dec 14 '12 at 15:37
  • Or this? http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – rajah9 Dec 14 '12 at 15:37

2 Answers2

0

I would try to investigate JavaCompiler class. Take a loot at this article.

Jan Krakora
  • 2,500
  • 3
  • 25
  • 52
0

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.