[英]Recursive method containing for loop return statement issue
这是用于家庭作业。 作业不是在递归上,而是在树结构上。 我的任务差不多完成了,但是我递归的方法打破了。 树结构由以下类给出:
package lab12;
import java.io.Serializable;
public class Dog implements Serializable{
public Dog[] children;
public String name;
public Dog(String name)
{
this.name = name;
}
@Override
public String toString()
{
return name;
}
}
我很确定原因是返回null。 语句与我的for循环结合使用。 for循环遍历不包含任何子节点的节点,结果返回null。 这样就结束了该方法,并将null传递回我的程序,这给了我null指针异常。
我无法删除return null语句,也不会编译,即使使用for循环将100%返回也是如此。
public Dog findParent(Dog root, String name)
{
String top = "Spot";
if(top.equals(name))
{
System.out.println("No further records");
System.out.println("Goodbye.");
System.exit(0);
}
for(int i = 0; root.children != null && i < root.children.length; i++)
{
if(root.children[i].name.equals(name))
{
return root;
}
else
{
return findParent(root.children[i], name);
}
}
return null; //Compiler still requires a return here.
}
我觉得在非void递归方法中使用for循环必须是一个普遍的问题。 有没有办法使编译器满意,但又没有多余的return null语句?
您的代码不能正常工作。 因为if和else子句都会返回。 这将导致循环仅执行索引0。您应该像下面那样更改代码:
public Dog findParent(Dog root, String name)
{
String top = "Spot";
if(top.equals(name))
{
System.out.println("No further records");
System.out.println("Goodbye.");
System.exit(0);
}
for(int i = 0; root.children != null && i < root.children.length; i++)
{
if(root.children[i].name.equals(name))
{
return root;
}
else
{
Dog parent = findParent(root.children[i], name);
if (parent != null)
return parent;
}
}
return null;
}
现在,您可以看到最后一个“返回null”是必要的。
在大多数情况下,编译器很聪明。 如果它发出警告,则应考虑代码的错误,而不是仅仅欺骗编译器以避免警告。
如果不完全理解此问题,我看不出“ return null”语句永远不会执行的原因。 也许您的其他声明应为:
return findParent(root.children[i], name);
此返回将确保一旦找到“父”,其值将被返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.