我在一个小型应用程序上工作,我想获得一个数学函数,并确定x(a,b)的范围并显示其图形。
在某种程度上,我调用了为x执行该函数的方法。
我的观点是我从TextField获得了函数(例如f(x)= 2 * x + 1)并将其用作Java代码
比方说:
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!!!!!
}
}
任何的想法?
最佳答案
您可以使用ScriptEngine。请参见下面的示例,您可以使其适应使用JTextField的内容。
注意:"2x+1"
不是有效的表达式,您需要包括所有运算符,因此在这种情况下:"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);
}
}
输出:
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