递归java方法,得到母亲,祖母,曾祖母等

时间:2012-03-26 16:39:20

标签: java recursion

我在文本文件中有一个列表Dogs,格式如下: ID:fatherid:motherid:出生:业主:品种 例如: 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;
}

我认为我需要的是递归方法,但我不知道如何做到这一点。

3 个答案:

答案 0 :(得分:1)

基本上,除非满足某些条件,否则您将创建一个使用其他参数调用自身的方法。

在您的情况下,您可以使用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指出此处不需要递归,所以请将其视为仅限学习练习。

答案 1 :(得分:0)

你不需要递归:你可以用WHILE替换你的IF,并在将母亲添加到String之后,将id替换为母亲的id。 (如果狗不存在时仍然需要留言,请在返回前检查输出是否为空。)

请注意,你有一个逻辑问题(我刚才描述的并没有解决):只是因为狗存在并不意味着它有一个母亲(或者你的循环/递归永远不会结束!),所以调用这个失踪母亲的任何方法都应该失败。

答案 2 :(得分:0)

它可以递归地完成(这在计算上很昂贵,但可能需要更简单的代码来理解)或者可以迭代地完成。这是一个迭代解决方案:

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()在数据库中没有母亲,则假设null返回aDog

相关问题