2016-03-07 114 views
-2

您好,我正在尝试在我的任务之一中实现递归。如何实现递归

这些是我的课程。

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; 
    } 
    } 
} 

// SNAKE 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; 
    } 
    } 
} 

// EAGLE 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; 
    } 
    } 
} 

基本上我试图找出递归是如何工作的动力()方法。测试人员期望得到26的值。但是,我的代码不起作用。我是新来的Java所以任何帮助表示赞赏。

//计

p1 = new Bear(
       new Bear(
        new Snake(
         new Snake(
         new Snake(
          new Bear(
           new Eagle())))))); 
+0

我没有看到任何递归 –

+0

那么你能看到为什么测试仪失败吗? –

+0

@SailorJerry这个问题不清楚。为什么以及如何power()返回26?你指的是哪个类的power()?你知道什么是递归吗? – user3437460

回答

0

根据您的意见,我认为您需要为每个班级添加TotemPole属性。然后在power()方法中,只需要计算它。例如在Bear类中您可以添加:

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; 
     } 
     } 
    } 

与其他类相同。 希望得到这个帮助。

0
  1. 没有任何关于Java中的递归比在任何其他语言递归不同。所以如果你知道递归,应该很容易用Java实现。

  2. 你想在这个代码中实现什么?

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

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

看看这段代码,例如:

new Bear(new Eagle()) 

贵熊类有这需要鹰对象作为参数的构造函数的任何? 编号 你在做什么和你需要做什么之间存在差距。

+0

基本上我需要测试仪的输出等于26.这是通过将所有power()方法一起添加完成的。所以它会是5 + 5 + 3 + 3 + 3 + 5 + 2。我试图理解如何做到这一点。 –

+0

输出并不重要。知道是什么让你将一个类的对象传递给另一个类的构造函数非常重要,这样你才能理解正确的概念。 – theLearner