我在理解递归如何工作时遇到一些问题,并且我有这个问题要求我使用递归打印菱形图案。一段时间后,我得到了一些接近我认为的解决方案的东西,但我的输出是这样的:
* * * * * *
* * * * *
* * * *
* * *
* *
*
*
* *
* * *
* * * *
* * * * *
* * * * * *
当它应该是这样的:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
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(" ");
}
}
}
我发现了一个非常相似的问题,并且有一个很好的解释,但我仍然很困惑,这就是我打开这个问题的原因,如果不允许,请关闭,但我真的被困住了。
如果有人能引导我朝正确的方向前进,告诉我我哪里出错了,那就太好了。
当第一次执行
printSpaces(totalHeight - currentRow);
时,参数将为0。这意味着第一个输出在第一个星号之前没有空格。然而您希望输出的第一行有最多空格。
因此,您应该让
currentRow
等于 1 而不是 6,并且在循环时使其递增,而不是递减。
因此将初始调用修复为:
diamond(6, 1);
并修复递归调用附近的
diamond
函数:
if (currentRow < 6) { // Changed condition
diamond(totalHeight, currentRow + 1); // increase
}