如何实现递归

How to implement Recursion

您好,我正在尝试在我的一项作业中实现递归。

这些是我的类。

public class Bear implements TotemPole {

  int bearCount;
  public Bear(TotemPole rest){}

  public Bear() {
    bearCount = 3;
  }

  public int power() {
    return  + 5;
  }

  public int height(){
    return bearCount + 5;
  }

  public boolean chiefPole(int bearCount){
    if(this.bearCount >= bearCount){
      return true;
    } else {
      return false;
    }
  }
}

// 蛇 CLASS

public class Snake implements TotemPole {

  public Snake(TotemPole rest){}
  int bearCount;

  public Snake() {
    bearCount = 0;
  }

  public int power() {
    return + 3;
  }

  public int height(){
    return bearCount + 1;
  }

  public boolean chiefPole(int bearCount){
    if(this.bearCount >= bearCount){
      return true;
    } else {
      return false;
    }
  }
}

// 老鹰 CLASS

public class Eagle implements TotemPole {

  int bearCount;
  public Eagle(){
    bearCount = 0;
  }

  public int power() {
    return + 2;
  }

  public int height(){
    return  bearCount + 1;
  }

  public boolean chiefPole(int bearCount){
    if(this.bearCount >= bearCount){
      return true;
    } else {
      return false;
    }
  }
}

基本上,我试图弄清楚递归如何适用于 power() 方法。测试人员期望获得 26 的值。但是,我的代码无法正常工作。我是 java 的新手,非常感谢您的帮助。

//测试人员

p1 = new Bear(
                new Bear(
                   new Snake(
                      new Snake(
                         new Snake(
                            new Bear(
                               new Eagle()))))));
  1. Java 中的递归与任何其他语言中的递归没有什么不同。所以如果知道递归,在Java.

  2. 中应该很容易实现
  3. 你想用这段代码实现什么?

    p1 = 新熊( 新熊( 新蛇( 新蛇( 新蛇( 新熊( 新鹰()))))));

为什么要将 1 个对象的引用作为参数传递给另一个 class 的构造函数?

看这段代码,例如:

new Bear(new Eagle())

你的classBear有没有以Eagle对象为参数的构造函数? 不。 你正在做的和你需要做的之间存在差距。

根据您的意见,我认为您需要为每个 class 添加 TotemPole 属性。然后在power()方法中,只需要计算一下即可。例如在class熊你可以添加:

class Bear implements TotemPole {

      int bearCount;
      TotemPole totem;
      public Bear(TotemPole totem){
          bearCount = 3;
          this.totem = totem;
      }


      public int power() {
          int result = 0;
          if(totem == null) {
              result = 5;
          } else {
             result = totem.power() + 5;
          }
        return result;
      }


      public Bear() {
        bearCount = 3;
      }

      public int height(){
        return bearCount + 5;
      }

      public boolean chiefPole(int bearCount){
        if(this.bearCount >= bearCount){
          return true;
        } else {
          return false;
        }
      }
    }

与其他 classes 相同。 希望对您有所帮助。