Java String to complete mathematical sum

后端 未结 3 675
礼貌的吻别
礼貌的吻别 2021-01-28 07:24

In java, I am currently in the process of trying to find a way to do mathematical sums by typing in text to a JTextField, putting it into a String, and converting it to an int a

3条回答
  •  醉话见心
    2021-01-28 08:07

    You can use the JavaScript engine:

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String expression = textField.getText();
    System.out.println(engine.eval(expression));
    

    Edit to allow all equations:

    All you have to do now to allow things like sin, cos, tan is this:

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String expression = textField.getText();
    
    // Between here...
            expression = expression.
                    replace("sin", "Math.sin").
                    replace("cos", "Math.cos").
                    replace("tan", "Math.tan").
                    replace("sqrt", "Math.sqrt").
                    replace("log", "Math.log").
                    replace("pi", "Math.PI");
    // And so on...
    
    System.out.println(engine.eval(foo));
    

    So then you can do something like:

    5 + 5 - 2 / 5 + sin(55) - log(20)
    

    Anything you want.

提交回复
热议问题