简体   繁体   中英

use value of Jtextfield as java code

I working on a small Application that I want to get a mathematical function, and range of x (a,b) and display the graph of it.

In some point I call a method that execute the function for a x. I'm stack on point that I get the function (ex. f(x)= 2*x+1 ) from TextField and use it as Java code

let's say:

class Myclass extends JFrame{
    blah blah ...
    JLabel lblFx =new JLebel("f(x=)");
    JTextfield Fx = new JTextField();

    //and lets say that this method calculate the f(x).
    //get as argument the x
    double calculateFx(double x){
        return  2*x+1; // !!!!BUT HERE I WANT TO GET THIS 2*x+1 FROM TextField!!!!!
    }

}

Any idea?

You can use a ScriptEngine. See an example below, that you can adapt to use the content of your JTextField.

Note: "2x+1" is not a valid expression, you need to include all the operators, so in this case: "2*x+1" .

public static void main(String[] args) throws ScriptException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    String formula = "2 * x + 1"; //contained in your jtextfield

    for (double x = 0; x < 10; x++) {
        String adjustedFormula = formula.replace("x", Double.toString(x));
        double result = (Double) engine.eval(adjustedFormula);
        System.out.println("x = " + x + "  ==>  " + formula + " = " + result);
    }
}

Output:

x = 0.0  ==>  2 * x + 1 = 1.0
x = 1.0  ==>  2 * x + 1 = 3.0
x = 2.0  ==>  2 * x + 1 = 5.0
x = 3.0  ==>  2 * x + 1 = 7.0
x = 4.0  ==>  2 * x + 1 = 9.0
x = 5.0  ==>  2 * x + 1 = 11.0
x = 6.0  ==>  2 * x + 1 = 13.0
x = 7.0  ==>  2 * x + 1 = 15.0
x = 8.0  ==>  2 * x + 1 = 17.0
x = 9.0  ==>  2 * x + 1 = 19.0

What you are looking for is called " eval " in some languages; however, Java has no such thing directly.

Java does have a scripting interface called " javax.script " which supports "eval" for code written in other languages (such as JavaScript, Ruby, Python, etc.) and also a tools package called " javax.tools " which provides access to the Java compiler (amongst other tools). For advanced programmers, another approach would be to use a parser generator to parse the string from the text field and interpret it somehow.

Unfortunately, these are advanced concepts for a beginner. Consider writing your program in another language which supports "eval" directly.

I found this awesome Expr lib!

"This package parses and evaluates mathematical expressions over floating-point numbers, like 2 + 2 or cos(x/(2*pi)) * cos(y/(2*pi)).

The design priorities were ease of use with helpful error messages, ease of integration into applets, and good performance: fast evaluation and short download times. Features and flexibility were not high priorities, but the code is simple enough that it shouldn't be hard to change to your taste."

In my example

class Myclass extends JFrame{
    blah blah ...
    JLabel lblFx =new JLebel("f(x=)");
    JTextfield Fx = new JTextField();
    String formula = Fx.getText();//2*x+1  OR  cos(x) OR lot of other functions

    //and lets say that this method calculate the f(x).
    //get as argument the x
    double calculateFx(double x){
        // The Expr Object that will representing the mathematical expression
        Expr expr = null;

        try {
            // parsing function formula to mathematical expression
            expr = Parser.parse(formula);
        } catch (SyntaxException e) {
            System.err.println(e.explain());
            return;
        }

        // Define(make) what will be the variable in the formula, here x
        Variable vx = Variable.make("x");
        // Set the given value(x) in variable
        vx.setValue(x);

        //return (mathematical) expression's value. See more for Expr lib how work...
        return expr.value();//
    }

}

finally when somewhere in your project call calculateFx(x) , for a given x, you will get the f(x) value!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM