我正在尝试使用ScriptEngine将String转换为等式。 我的代码要求一个线性方程和X的值。之后它将x替换为值。 当我尝试在“()”之后添加“*”时它不起作用,因此它不会评估字符串方程
package known;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import java.util.Scanner;
import static java.util.stream.DoubleStream.concat;
import javax.script.ScriptException;
/**
*
* @author netof
*/
public class Known {
/**3
* @param args the command line arguments
*/
public static void main(String[] args) throws ScriptException {
System.out.println("Insert your equation");
Scanner sc = new Scanner(System.in);
String equation = sc.nextLine();
System.out.println("Insert value for X");
String x = sc.nextLine();
System.out.println();
String test = equation.replace("x","("+x+")");
if(test.contains("("+x+")")){
String replace = test.replace("("+")", "*");
System.out.println(replace);
}else{
System.out.println("Can't Replace");
}
}
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String convert = replace;
System.out.println(engine.eval(replace));
}
答案 0 :(得分:0)
您是否尝试将x设为int而不是String?
int x = sc.nextIn();
或者您可以将String x解析为int
String x = sc.nextLine(); int xx = Integer.parseInt(x);
只是几点建议。