下面是我的代码,可以使用用户输入一些简单的问候或鼠标并搜索字符串(我稍后将在更大的文本文件中使用此代码)。
我用它来创建一个使用contains方法的Java代码行。之后,我需要对其进行评估。我在使用脚本引擎时获得了一些帮助,但是仍然出现此错误:Exception in thread "main" javax.script.ScriptException: ReferenceError: "name" is not defined in <eval> at line number 1
来自我要评估的代码的输出为name.contains("hello") || name.contains("mouse")
。
任何帮助都会很棒。谢谢
public static void main(String args[]) throws ScriptException {
String searchString = "name";
String terms = "(hello) || (mouse)";
String command = "";
//multiple commands
if(terms.contains("(") && terms.contains(")") && terms.contains("[") && terms.contains("]")){
command = terms.replace(")","\")");
command=command.replace("(", searchString + ".contains(\"");
command = command.replace("[","(");
command = command.replace("]",")");
}
//only ands/ only ors
else {
command = terms.replace("(", searchString + ".contains(\"");
command = command.replace(")", "\")");
}
System.out.println(command);
String name = "mousehellonamepe";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval(command);
System.out.println(result);
答案 0 :(得分:0)
您到底想做什么?
=======更新====== 首先,字符串术语应为列表。
制作:
ArrayList<String> searchTerms = new ArrayList();
向列表中添加任意多个单词,如下所示:
// using add() to initialize values
arr.add("Hello");
arr.add("Mouse");
arr.add("Bike");
arr.add("House");
// use contains() to check if the element
// 2 exits or not
boolean mouseExists = arr.contains("Mouse");
if (ans)
System.out.println("Our list contains the word mouse");
else
System.out.println("Our list does not contain the word mouse");
这应该输出以下内容:
Our list contains the word mouse
代码应如下所示:
public static void main(String args[]) throws ScriptException {
ArrayList<String> searchTerms = new ArrayList();
arr.add("Hello");
arr.add("Mouse");
arr.add("Bike");
arr.add("House");
boolean mouseExists = arr.contains("Mouse");
if (ans)
System.out.println("Our list contains the word mouse");
else
System.out.println("Our list does not contain the word mouse");
}
答案 1 :(得分:0)
Interpreter i = new Interpreter();
i.set("searchThis", searchString);
i.set("answer", i.eval(command));
Boolean answer2 = (Boolean) (i.get("answer"));
http://www.beanshell.org/manual/quickstart.html#Calling_BeanShell_From_Your_Application
我用它来评估命令。 上面的链接提供了所有解释!