1 回答

TA貢獻1773條經驗 獲得超3個贊
我認為第一步是makeDesign1()正確地重新定義。我們想為我們的繪圖傳遞一個尺寸。我們還想稍微改變邊界,讓大小為 1 的時候畫一顆星,而不是像原來的那樣:
public static void makeDesign(int n)
{
for (int i = 0; i < n; i++) // For loop is the one creating the rows
{
for (int x = n; x > i; x--) // Nested loop is the one creating the columns
{
System.out.print("*");
}
System.out.println();
}
System.out.println();
}
下一步是讓兩個循環都倒計時到 1,以在時機成熟時簡化遞歸:
public static void makeDesign(int n)
{
for (int i = n; i > 0; i--) // For loop is the one creating the rows
{
for (int x = i; x > 0; x--) // Nested loop is the one creating the columns
{
System.out.print("*");
}
System.out.println();
}
System.out.println();
}
現在我們可以簡單地將每個循環轉換成它自己的遞歸函數,一個調用另一個:
public static void makeDesign(int n)
{
if (n > 0)
{
makeDesignRow(n);
makeDesign(n - 1);
}
else
{
System.out.println();
}
}
public static void makeDesignRow(int x)
{
if (x > 0)
{
System.out.print("*");
makeDesignRow(x - 1);
}
else
{
System.out.println();
}
}
輸出
傳遞makeDesign()一個 10 的參數,我們得到:
> java Main
**********
*********
********
*******
******
*****
****
***
**
*
>
添加回答
舉報