我試圖遞歸調用一個方法,直到我獲得所需的輸出。但是,我想調用另一個類的方法並從該方法獲取信息,以便在遞歸方法中使用它。例如,假設我有稱爲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.
}
}
你的問題不是很清楚,請張貼一些代碼,即已創建 –