递归实现Java菱形图案输出异常,请求排查修正方向
递归实现Java菱形图案的顺序问题排查
我在理解递归逻辑时遇到困难,尝试用递归实现Java菱形图案输出,结果接近预期但顺序不符合要求,希望得到错误排查方向。
当前输出
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
期望输出
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
当前代码
public class DiamondPattern { public static void main(String[] args) { diamond(6, 6); } public static void repeatlyPrint(int amount, String pattern) { if (amount > 0) { // print a pattern once System.out.print(pattern); // recursively call the function itself repeatlyPrint(amount - 1, pattern); } } public static void diamond(int totalHeight, int currentRow) { printSpaces(totalHeight - currentRow); // print spaces (outside of diamond) repeatlyPrint(currentRow , "* "); // print asterisks and spaces System.out.println(); if (currentRow > 1) { diamond(totalHeight, currentRow -1); } printSpaces(totalHeight - currentRow); // print spaces repeatlyPrint( currentRow, "* "); // print asterisks and spaces System.out.println(); } private static void printSpaces(int count) { for (int i = 0; i < count; i++) { System.out.print(" "); } } }
错误分析
你的递归逻辑顺序搞反了。当前diamond方法的执行流程是:
- 先打印当前行(从6到1,星星数递减)
- 递归调用
currentRow-1,直到currentRow=1 - 递归返回后,再打印当前行(从1到6,星星数递增)
这就导致输出的上半部分是递减的菱形,下半部分是递增的,和期望的顺序完全相反。
修改方案
调整递归方向和打印顺序,让程序先从最小行(星星数1)开始递归到最大行(星星数6),先打印上半部分递增的菱形,再递归返回打印下半部分递减的菱形:
- 把
main方法里的初始调用改成diamond(6, 1),从第1行开始而不是第6行 - 修改
diamond方法的递归条件:当currentRow < totalHeight时,递归调用currentRow+1,而不是currentRow>1时调用currentRow-1 - 保持打印逻辑的位置,先打印当前行再递归,递归返回后再次打印当前行
修改后的完整代码:
public class DiamondPattern { public static void main(String[] args) { diamond(6, 1); // 初始调用从第1行开始 } public static void repeatlyPrint(int amount, String pattern) { if (amount > 0) { System.out.print(pattern); repeatlyPrint(amount - 1, pattern); } } public static void diamond(int totalHeight, int currentRow) { // 打印上半部分的当前行 printSpaces(totalHeight - currentRow); repeatlyPrint(currentRow, "* "); System.out.println(); // 递归到下一行,直到达到总行数 if (currentRow < totalHeight) { diamond(totalHeight, currentRow + 1); } // 递归返回后,打印下半部分的当前行 printSpaces(totalHeight - currentRow); repeatlyPrint(currentRow, "* "); System.out.println(); } private static void printSpaces(int count) { for (int i = 0; i < count; i++) { System.out.print(" "); } } }
这样执行后,输出就会和期望的完全一致。
内容的提问来源于stack exchange,提问作者mattia
相关产品推荐
相关产品推荐

