我正在开发一个小型应用程序,我想要获取数学函数和 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!!!!!
}
}
有什么想法吗?
最佳答案
您可以使用脚本引擎。请参阅下面的示例,您可以调整该示例以使用 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
关于java - 使用 Jtextfield 的值作为 java 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11690140/