1

我有以下课程

class ListNode
{
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

我的任务是编写一个方法:

  1. 作为int[]参数。
  2. 反转数组。
  3. 返回ListNode数组中当前元素的值,.next新创建的 ListNode 与数组中的相应值,依此类推。

给定new int[]{0, 8, 7};I expect to get a ListNodewhere value is 7 的输入,.next是一个值为 8 的新节点,最后.next.next是一个值为 0 的新节点。

我编写了以下方法来完成这种行为

public static ListNode reverseAndLinkToListNode(int [] arrayToReverse)
{
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");

    int finalDigitsArrayLength = arrayToReverse.length;

    ListNode finalNode = new ListNode();

    if (finalDigitsArrayLength > 0)
    {
        finalNode.val = arrayToReverse[finalDigitsArrayLength - 1];
        int j = 1;

        for (int i = finalDigitsArrayLength - 2; i >= 0; i--)
        {
            try
            {
                // create a new list node
                ListNode newlyCreatedNode = new ListNode(arrayToReverse[i]);
                // calculate how many 'nexts' I need
                String codeToExecute = returnNumberOfNexts(j);
                // set the next field with the list node I just created
                engine.eval(codeToExecute);
            }
            catch (Exception e)
            {
                System.out.println(e);
            }

            j++;
        }
    }

    return finalNode;
}


public static String returnNumberOfNexts(int nextCounter)
{
    String finalDotNextString = "finalNode";

    if (nextCounter > 0)
    {
        for (int i = 0; i < nextCounter; i++)
        {
            finalDotNextString += ".next";
        }
    }

    finalDotNextString += " = newlyCreatedNode;";

    return finalDotNextString;
}

上面的解决方案返回要执行的正确代码,但是在执行时,我得到:

javax.script.ScriptException: ReferenceError: "finalNode" is not defined in <eval> at line number 1

如何在引擎中定义finalNode和变量?newlyCreatedNode

4

1 回答 1

1

您的脚本引擎在尝试解析“finalNode”变量时失败。原因是 finalNode 在 Java 中是已知的,但在 Javascript 引擎中却不是。所以你需要告诉脚本引擎如何解析变量。我没有测试代码,但它可能看起来有点像这样:

ListNode finalNode = new ListNode();
ScriptEngine engine = manager.getEngineByName("js");
Bindings bindings = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
if (bindings==null) {
    bindings = engine.createBindings();
    engine.setBindings(ScriptContext.GLOBAL_SCOPE);
}
bindings.put("finalNode", finalNode);
engine.eval(codeToExecute);
于 2021-09-20T20:40:43.230 回答