我将基本情况指示为 emptySpace=0
,而 else if 条件将基本情况指示为 star=0
。我原以为程序会在打印星星之后先打印空格,但发生了相反的情况。它不应该先打印空格然后再打印星星吗?
public static void displayStarss(int emptySpace, int star) {
if (emptySpace != 0) {
displayStarss(emptySpace - 1, star);
System.out.print(" ");
} else if (star != 0) {
displayStarss(emptySpace, star - 1);
System.out.print("*");
}
}
public static void main(String[] args) {
displayStarss(3, 3);
}
最佳答案
它按照您的命令执行操作:
displayStarss(3, 3);
-> displayStarss(2, 3);
-> -> displayStarss(1, 3);
-> -> -> displayStarss(0, 3);
-> -> -> -> displayStarss(0, 2);
-> -> -> -> -> displayStarss(0, 1);
-> -> -> -> -> -> displayStarss(0, 0);
-> -> -> -> -> System.out.print("*");
-> -> -> -> System.out.print("*");
-> -> -> System.out.print("*");
-> -> System.out.print(" ");
-> System.out.print(" ");
System.out.print(" ");
关于java - 为什么递归函数首先执行最后一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56938231/