gpt4 book ai didi

java - 递归java方法,获取母亲、祖母、曾祖母等

转载 作者:行者123 更新时间:2023-12-01 15:28:31 25 4
gpt4 key购买 nike

我在文本文件中有一个狗列表,格式如下:id:父亲:母亲:出生:所有者:品种前任:3:2:1:2000:斯科蒂:彼得:达克斯

然后我用狗的对象填充数组列表。我需要一个方法来返回给定 id 的狗的所有母亲。我已经有以下方法:getMother、getDog、getChildren、getParents、existDog。 getDog 和 getMother 返回一个 Dog,getChildren 和 getParents 返回一个 String。现在我需要一种方法来给我母亲、祖母、曾祖母等等。我不知道如何制作这个方法。这段代码给了我一只狗的母亲和祖母:

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() (或某些调整后的方法):

public String getMotherTree(int id) {
String output = "";
if (existDog(id)) {
Dog mother = GetMother(id);
output += mother.toString();
int morId = mother.getId();
return output + ", " + getMotherTree(morId); //recursion
}

//return an empty string if the dog doesn't exist
//this basically ends the recursion
return output;
}

正如 BalusC 指出的,这里不需要递归,因此请将其仅视为学习练习。

关于java - 递归java方法,获取母亲、祖母、曾祖母等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9876133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com