变量名称无法解析为变量 - 我找不到问题所在



在第 110 行,它说"return front3",我收到此错误。我不知道为什么,我在 while 循环中创建节点 front3。

    public static Node add(Node poly1, Node poly2) {
        /** COMPLETE THIS METHOD **/
        // FOLLOWING LINE IS A PLACEHOLDER TO MAKE THIS METHOD COMPILE
        // CHANGE IT AS NEEDED FOR YOUR IMPLEMENTATION
        Node ptr1 = poly1;
        Node ptr2 = poly2;
        Node ptr3 = null;
        // Node front3;
        while (ptr1 != null && ptr2 != null) {
            if (ptr1.term.degree == ptr2.term.degree) {
                if (ptr3 == null) {
                    Node front3 = new Node(ptr1.term.coeff + ptr2.term.coeff,ptr1.term.degree,null);
                    ptr3 = front3;
                } else {
                    Node temp = new Node(ptr1.term.coeff + ptr2.term.coeff,ptr1.term.degree,null);
                    ptr3.next = temp;
                    ptr3 = temp;
                }
                ptr1 = ptr1.next;
                ptr2 = ptr2.next;
            } else if ( ptr1.term.degree > ptr2.term.degree) {
                if (ptr3 == null) {
                    Node front3 = new Node(ptr1.term.coeff,ptr1.term.degree,null);
                    ptr3 = front3;
                } else {
                    Node temp = new Node(ptr1.term.coeff, ptr1.term.degree , null);
                    ptr3.next = temp;
                    ptr3 = temp;
                }
                ptr1 = ptr1.next;
            } else if ( ptr1.term.degree < ptr2.term.degree ) {
                if (ptr3 == null) {
                    Node front3 = new Node(ptr2.term.coeff, ptr2.term.degree,null);
                    ptr3 = front3;
                } else {
                    Node temp = new Node(ptr2.term.coeff,ptr2.term.degree,null);
                    ptr3.next = temp;
                    ptr3 = temp;
                }
                ptr2 = ptr2.next;
            }
        }

        if (ptr3 == null) {
            return null;
        }
        return front3;
    }

然后我创建了一个不同的节点,Node front4,将其初始化为某种东西,我的程序运行了。这是在 while 循环之外完成的。

发生这种情况是因为对象仅存在于声明它们的块中。在您的情况下,您的front3将仅存在于您用于声明它的if块中:

if (ptr3 == null) {
    Node front3 = new Node(ptr2.term.coeff, ptr2.term.degree,null);
    ptr3 = front3; // Can use it here
}
// Cannot use it here

如果你真的需要返回front3对象,你应该在"方法级别"中声明它,就像你对ptr节点所做的一样。事实上,你已经在那里评论了。如果您只是按以下方式应用更改,您应该很高兴:

当前:

// Node front3;

后:

Node front3 = null; // Needs to initialize

您的if语句应更改为以下示例:

当前:

if (ptr3 == null) {
    Node front3 = new Node(ptr1.term.coeff,ptr1.term.degree,null);
    ptr3 = front3;
}

后:

if (ptr3 == null) {
    front3 = new Node(ptr1.term.coeff,ptr1.term.degree,null); // No need for "Node", as it was already declared
    ptr3 = front3;
}

附言。我没有审查逻辑。这只是为了解释为什么您收到"无法将变量名称解析为变量">错误。

最新更新