我正在尝试编写一个Java例程来评估简单的数学表达式,String例如:
"5+3""10-40""10*3"我想避免很多if-then-else语句.我怎样才能做到这一点?
在我的一个项目中,我想添加一个功能,例如用户可以在公式中提供
sin (x + pi)/2 + 1
Run Code Online (Sandbox Code Playgroud)
我在我的Java应用程序中使用它
/**
* The formula provided by the user
*/
private String formula; // = "sin (x + pi)/2 + 1"
/*
* Evaluates the formula and computes the result by using the
* given value for x
*/
public double calc(double x) {
Formula f = new Formula(formula);
f.setVar("x", x);
return f.calc();
// or something similar
}
Run Code Online (Sandbox Code Playgroud)
我如何评估数学表达式?