【发布时间】: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