1
public static String formulaCalcularRenda = "(Loja.getRendaFixa()*(1+super.getArea()/100)+super.getReceita()/100)";

@Override
    public double calcularRenda(){
        return (Loja.getRendaFixa()*(1+super.getArea()/100)+super.getReceita()/100);
    }

My main objective is to reuse the code, while being the formula altered by order of the user itself. I've tried something similar before, but I was uncapable to succeed, because the string has letters.

@Override
        public double calcularRenda(){
            return Double.parseDouble(Loja.formulaCalcularRenda);
        }

Can someone help me?

Lau13
  • 128
  • 1
  • 3
  • 10
  • Always good to tag your question with the language you're working in ;) – Madbreaks Apr 03 '15 at 21:16
  • 1
    You want the user to be able to enter arbitrary Java code and have your program execute it? That doesn't sound like a great idea, and I'm not sure a user would want or even be able to write sensible Java for your function... – Mattias Buelens Apr 03 '15 at 21:20
  • 1
    Even if the user was able to input syntactically correct Java you'd still need to write your own Java interpreter. Which you already have so why reinvent? That's my thought at least when I end up in the compiler design realm. – John Apr 03 '15 at 21:22
  • Maybe this [Dynamic Compilation](http://stackoverflow.com/a/2946402) example can help. Apart from that there's `ScriptEngineManager` that allows you to dynamically run scripts that are available for use. – Aman Agnihotri Apr 03 '15 at 21:42

2 Answers2

0

As others are commenting, this is not an easy or generally wise thing to do. But if you are committed to this task, a scripting language is a much better choice for the expression evaluation. Scripting language support is built into Java and is relatively easy to use.

The Java javascript programmer guide would be a good place to start. It has examples that you should be able to adapt to your needs.

Martin Serrano
  • 3,727
  • 1
  • 35
  • 48
0

If you think about it, it doen't make too much sense for the user to write the code. So, in your opinion, what would be the best way for me, not to repeat the same code, over and over again?

Lau13
  • 128
  • 1
  • 3
  • 10