((((15>=1 && 50>=10) || (60>=1 && 40>=21)) && (20<50)) || (60>=1 && 20>=17))
in this case:- [WORKING AS PER EXPECTATION]
current output -- (15>=1 && 50>=10) && (20<50)
the expected output is -- (15>=1 && 50>=10) && (20<50)
((((15>=1 && 50>=10) || (60>=1 && 40>=21)) && (200<50)) || (60>=1 && 20>=17))
in this case:- [FAILED]
current output -- (15>=1 && 50>=10), (60>=1 && 20>=17) -- [(15>=1 && 50>=10) // 200<50 is false so this one should not come]
the expected output is -- (60>=1 && 20>=17)
javascript引擎名称:OracleNashorn
发动机版本:11.0.25<50)
为什么我的代码不是产生预期的结果?这是我到目前为止尝试过的: -
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.*;
import java.util.regex.*;
public class ExpressionSplitter
{
public static void Runner()
{
String expression = "((((15>=1 && 50>=10) || (60>=1 && 40>=21)) && (20<50)) || (60>=1 && 20>=17))";
try
{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String loggedExpression = wrapExpressionsWithLogging(expression);
Bindings bindings = engine.createBindings();
Object result = engine.eval(loggedExpression, bindings);
List<String> trueConditions = (List<String>) bindings.get("trueConditions");
} catch (ScriptException e) {
e.printStackTrace();
}
}
private static String wrapExpressionsWithLogging(String expression) {
Pattern pattern = Pattern.compile("\\(([^()]+)\\)");
Matcher matcher = pattern.matcher(expression);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String subExpression = matcher.group(1);
matcher.appendReplacement(sb, "logResult((" + subExpression + "), '" + subExpression.replace("'", "\\'") + "')");
}
matcher.appendTail(sb);
return "var trueConditions = []; function logResult(result, expression) { if(result){trueConditions.push(expression)}; return result; }" + sb.toString() + "; trueConditions;";
}
}
为什么我的代码不是产生预期的结果?
因为您的方法是不可行的。
程序提出了该表达式,以提取括号的子表达,而无需任何嵌套括号。 然后,它将每个人作为JavaScript表达式评估,并报告哪些评估为true。 这根本无法解决您提出的问题,因为它不考虑所测试的表达式的上下文,例如它们是否出现在评估错误的较大表达式中,或者是短路评估是否可以防止对它们进行评估全部我认为提出的程序不可挽救。 您需要完全不同的东西。
没有看到此练习的说明,我想它希望您为表达语言写一个完整的解析器。 您需要对输入表达式结构的洞察力,以便能够识别和修剪您不需要的部分。 特别有可能您希望使用最近在课程中涵盖的技术。 例如,也许是递归的解析和 /或抽象的语法树,尽管可以替代两种练习的替代方法。