java - 作业 : Magic Plant Recursion Exercise in Java

标签 java eclipse recursion

<分区>

明确地说,这是我的编程 II 类(class)的评分作业。我通常很容易接受新的编程概念,但这个关于递归的特殊任务真的让我很吃力,我正在寻找正确方向的一些好的插入。下面是逐字的作业和我目前已有的代码。

魔法植物

我们有一种神奇的植物,一旦种下,它就会在第一年发芽并长出两片叶子。它的叶子每年翻一番,除了每三年它的叶子增加三倍。像这样的东西:

Link to table displayed in my homework document

编写一个名为 MagicPlant 的类,其中包含以下方法:

  • 返回给定植物年龄的叶子数量的方法
  • 一种非递归方法,根据叶子的数量返回植物的年龄。
  • 一种递归方法,根据叶子的数量返回植物的年龄。

在驱动类中测试方法。

找出您的算法和数据结构可以处理的最大(最古老)植物。


这就是我得到的,我在最后一个要点上遇到了麻烦,在第二个要点上也有点困惑(但我的代码似乎可以工作)。

我当前的代码不包括 Driver 类,因为它只是调用语句:

public class MagicPlant {

    // Method that returns the number of leaves given
    // the age of the plant.
    public int getLeaves(int age) {
        int leafCount = 1;
        for (int i = 1; i <= age; i++) {
            if (i % 3 != 0) {
                leafCount *= 2;
            } else {
                leafCount *= 3;
            }
        }
        return leafCount;
    }

    // Non-recursive method that returns the age of the plant
    // given the number of leaves.
    public int getAgeNR(int leaves) {
        int age = 1;
        while (leaves > getLeaves(age)) {
            age++;
        }
        return age;
    }

    // Recursive method that returns the age of the plant
    // given the number of leaves.
    public int getAgeR(int leaves) {
        return 0;
    }
}

最佳答案

我的建议是,用递归替换 while 循环。因此,您没有局部变量,而是将该变量返回到方法中(递归)。

此外,我建议您为递归创建 2 种方法:

public int getAgeR(int leaves){
     return getAgeR(1, leaves); // call overload with initial value
}

private int getAgeR(int age, int leaves){
     // do your magic here
}

关于java - 作业 : Magic Plant Recursion Exercise in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47077299/

相关文章:

java - 定义具体方法的接口(interface) - 在什么情况下允许这样做?

java - 如何删除空白?

c++ - C++中的递归

c - 我需要使用 C 的合并原则递归地从列表中删除重复项

Java 无法保存我的输入。看我的代码

java - 多次运行特定的 JUnit 测试,但排除其他测试多次运行

java - 如果 day 是该月的第一天,Joda 或 Java 如何返回 true?

php - 如何在 Eclipse 中使用 PHPdoc

java - 如何在 Android 中通过 String 使 SearchList 工作?

c# - 使用递归从 IDictionary 中删除项目