在第110行,它说“ return front3”,我得到了这个错误。我不知道为什么,我在while循环中创建Node 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;
}


附言我没有审查逻辑。这只是为了解释为什么您会收到“变量名无法解析为变量”错误的原因。

08-03 22:29