在第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循环之外完成的。
答案 0 :(得分:1)
发生这种情况是因为对象仅存在于声明的块内。对于您而言,您的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;
}
Ps。我没有审查逻辑。这只是为了解释为什么出现“变量名无法解析为变量” 错误。