递归java方法,获取母亲、外祖母、外祖母等
我有一个文本文件中的狗列表,格式如下: id:fatherid:motherid:born:owner:Fred 前任: 3:2:1:2000:Scotty:Peter:dachs 然后我用dog的对象填充一个数组列表。我需要一个方法,返回一个给定id的狗的所有母亲。我已经有了:getMother、getDog、getChildren、getParents、existDog的方法。getDog和getMother返回一只狗,getChildren和getParents返回一个字符串。现在我需要一种方法,给我母亲,祖母,伟大的祖母等等。我不知道怎么做这个方法。这个密码给了我一条狗的母亲和祖母:递归java方法,获取母亲、外祖母、外祖母等,java,recursion,Java,Recursion,我有一个文本文件中的狗列表,格式如下: id:fatherid:motherid:born:owner:Fred 前任: 3:2:1:2000:Scotty:Peter:dachs 然后我用dog的对象填充一个数组列表。我需要一个方法,返回一个给定id的狗的所有母亲。我已经有了:getMother、getDog、getChildren、getParents、existDog的方法。getDog和getMother返回一只狗,getChildren和getParents返回一个字符串。现在我需要一
public String getMotherTree(int id) {
String output = "";
if (existDog(id)) {
Dog mother = GetMother(id);
output += mother.toString();
int morId = mother.getId();
Dog grandMother= GetMother(motherId);
output += grandMother.toString;
return output;
}
output = "The dog with that id do not exist!";
return output;
}
我想我需要的是一个递归方法,但我不知道如何做到这一点。基本上,除非满足某些条件,否则您将创建一个使用另一个参数调用自身的方法 在您的情况下,您可以使用
getMotherTree()
(或一些调整后的方法):
正如BalusC指出的,这里不需要递归,因此请将其视为一种学习练习。您不需要递归:您可以用一段时间替换IF,在将母字符串添加到字符串后,将id替换为母字符串的id。(如果狗不存在,您仍然需要消息,只需在返回前检查输出是否为空。)
请注意,您有一个逻辑问题(我刚才描述的问题并没有解决):仅仅因为狗存在并不意味着它有一个母亲(或者您的循环/递归永远不会结束!),所以对这个缺失母亲的任何方法的调用都应该失败 它可以递归完成(这在计算上很昂贵,但可能更容易理解代码),也可以迭代完成。下面是一个迭代解决方案:
public String getMotherTree(int id) {
if (!existDog(id)) {
return "The dog with that id do not exist!";
}
StringBuilder output = new StringBuilder();
for (Dog mother = GetMother(id); mother != null; mother = mother.getMother()) {
if (output.length() > 0) {
output.append(", ");
}
output.append(mother.toString());
}
return output.toString();
}
这假设
aDog.getMother()
如果aDog
在数据库中没有母亲,则返回null
。狗母亲是1:1关系,因此这也可以在for
或while
循环中完成。递归方法是不必要的。好的,你能给我举个例子吗?这个例子是不正确的。您不应该返回递归调用的结果。这样,您只会得到输出中最上面的母亲,而OP需要将它们全部链接起来。您应该将其添加到输出
@BalusC oops,删除太多;),我会解决的。@Twistar是的,您需要检查mother
是否也为空。我把它留给你做练习:)我也去掉了空指针:)再次感谢你!
public String getMotherTree(int id) {
if (!existDog(id)) {
return "The dog with that id do not exist!";
}
StringBuilder output = new StringBuilder();
for (Dog mother = GetMother(id); mother != null; mother = mother.getMother()) {
if (output.length() > 0) {
output.append(", ");
}
output.append(mother.toString());
}
return output.toString();
}