【问题标题】:How do I call a method recursively?如何递归调用方法?
【发布时间】:2016-03-02 07:38:29
【问题描述】:

我正在尝试递归调用一个方法,直到获得所需的输出。但是,我想从另一个类调用一个方法并从该方法获取信息,以便在我的递归方法中使用它。例如,假设我有一个名为 Cake 的父类,其中包含有关蛋糕的信息,例如其面糊(即面糊的数量),一个具有特定类型蛋糕的扩展类,其中包含面糊的唯一实例,并且我有另一个名为Bakery 的课程我想实际制作正在订购的蛋糕。我在Bakery 中有一个名为createCake 的方法,我想递归调用此方法,直到锅中有足够的面糊来制作蛋糕。如果面糊的数量是在扩展类中随机生成的,我如何从该类中调用getBatter 方法并捕获面糊数量的信息,以便在我的递归方法中使用它来创建蛋糕?谁能帮我解决这个问题?我正在做类似的事情,但我不太明白我将如何实际获取信息以使递归工作。我有一个下面的代码示例,以便您了解我正在尝试做什么(我知道这不是很准确)。任何帮助将不胜感激。

import java.util.Random;

public abstract class Cake
{
   static Random gen = new Random(System.currentTimeMillis());

   public int type; //type of cake
   public static int batter = gen.nextInt() * 3; //random amount of batter

   public int getType()
   {
     return type;
   }

   public int getBatter()
   {
      return batter;
   }
}


public class RedVelvet extends Cake
{
  public int type;
  public int batter = gen.nextInt(3)+6; //generates between 6-8 cups of batter inclusive

  public int getType()
  {
    return 1;
  }
  public int getBatter()
  {
    return batter;
  }
}

public class Chocolate extends Cake
{
  public int type;
  public int batter = gen.nextInt(3)+6; //generates between 6-8 cups of batter inclusive

  public int getType()
  {
    return 2;
  }
  public int getBatter()
  {
    return batter;
  }
}


public class Pound extends Cake
{
  public int type;
  public int batter = gen.nextInt(3)+6; 

  public int getType()
  {
    return 3;
  }
  public int getBatter()
  {
    return batter;
  }
}

public class Bakery
{
  import java.util.Scanner;
  System.out.print("Enter desired size of cake to be baked (Must be at least 12):");
  desiredSize=scan.nextInt();

  public static void createCake(int desiredSize, int currentSize) //currentSize is the current amount of batter in the pan
  {
    if (currentSize == desiredSize)
      return;
   else if (currentSize < desiredSize)
   {
     //Recursively call createCake method so that batter continues to be added to the pan until there is enough to make the desired cake size. I want to get the batter information from one of the extended classes in order to add it to the cake.
   }
}

【问题讨论】:

  • 您的问题不是很清楚,请贴一些代码,即您创建的类

标签: java inheritance recursion methods


【解决方案1】:

这是为了学校还是某种课程,因为我个人不会走这条路,但那又是我的看法。就像,我对烘焙到底了解多少,我可以有把握地告诉你……绝对没有。有些人甚至可能会说我的编程/编码技能,但话又说回来,我不是程序员,我在几乎所有的编程环境中都是自学的,包括我现在已经忘记的大部分旧程序集。 :/

我应该认为,在烘焙蛋糕(或与此相关的大多数事情)时,必须建立某种准确性以避免浪费,我们都知道浪费会花钱。我不太相信生成随机数量的蛋糕面糊对于您最有可能尝试完成的任务来说足够准确,但话又说回来,您已经知道这一点。我注意到在你的不同蛋糕类中,它们基本上都会生成一个从 6 到 8 的随机数。如果它们都做同样的事情,那么为什么要有它们?

我认为您根本不需要递归,而是需要一个从循环中调用的简单方法,例如:

while (currentSize < desiredSize) {
    currentSize+= getBatter(cake, desiredSize);
}

我会这样做,如果你发现这完全没有意义,我现在道歉:

import java.util.Random;
import java.util.Scanner;

public class Bakery {


    public static void main(String[] args) {
        getBaking();  // :)

    }


    private static void getBaking(){
        Scanner scan = new Scanner(System.in); 

        String cakeType = "";
        while (cakeType.equals("")) {
            System.out.print("Enter desired cake to be baked (Pound, Chocolate, "
                    + "RedVelvet) or\nenter 'exit' to quit: -> ");
            cakeType = scan.nextLine();
            if (cakeType.isEmpty()) { 
                System.out.println("\nYou must supply the name of cake to bake or "
                        + "enter 'exit' to quit!\n"); 
            }
            else if (cakeType.toLowerCase().equals("exit")) { System.exit(0); }
            else if (!cakeType.toLowerCase().matches("(pound|chocolate|redvelvet)")) {
                System.out.println("\nYou must supply the name of cake as shown above!\n");
                cakeType = "";
            } 

        }

        int desiredSize = 0;
        String size = "";
        while (size.equals("")) {
            System.out.print("\nEnter desired size of cake to be baked (must be at "
                    + "least 12\"): -> ");
            size = scan.nextLine();
            if (size.isEmpty()) { 
                System.out.println("\nYou must supply the size of cake to bake or "
                        + "enter 'exit' to quit!\n"); 
            }
            else if (size.toLowerCase().equals("exit")) { System.exit(0); }
            else if (Integer.valueOf(size.replace("\"","")) < 12 ) {
                System.out.println("\nYou must supply a cake size of 12\" or greater!\n");
                size = "";
            } 
        }
        desiredSize = Integer.valueOf(size.replace("\"",""));

        createCake(cakeType, desiredSize, 0);
    }

    public static void createCake(String cake, int desiredSize, int currentSize) {
        //currentSize is the current amount of batter in the pan
        while (currentSize < desiredSize) {
            currentSize+= getBatter(cake, desiredSize);
            System.out.println(currentSize);
        }

        System.exit(0); // Done! - Quit!
    } 

    public static int getBatter(String cake, int desiredSize) {
        Random gen = new Random(System.currentTimeMillis());
        // Since the random generation for the batter amount is the
        // same for all cake types according to your code we just 
        // need this:
        int batterAmount = gen.nextInt(3)+6;

        // But if we want to be more specific for each Cake Type
        // then we can do it this way but first create the required 
        // batter equations for each cake type and remove the /* and 
        // */ from the code but first comment out (//) the batterAmount
        // variable declaration above.
        // NOTE: Both cake diameter AND 'Height' should play into the factor
        // of how much batter is required unless of course all cakes made are
        // of the same height.
        /*
        int batterAmount = 0;
        switch (cake.toLowerCase()) {
            case "pound":
                batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
                break;
            case "chocolate":
                batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
                break;
            case "redvelvet":
                batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
                break;
        } */

        return batterAmount;
    }   
}

嗯,我确实希望这对你有所帮助,或者至少让你有点想法:P

【讨论】:

  • @DevilHnd 嗨,我认为 while 循环也是一个更好的解决方案,但我必须使用递归。我只是不确定如何去做,所以我只是想出了一个与我正在研究的问题类似的问题。不过感谢您的帮助:)!
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 2021-11-07
  • 1970-01-01
  • 2019-09-29
相关资源
最近更新 更多