java 打印 排序 数字塔_Java数据结构递归——打印数字塔

数据结构课上,老师讲的数字塔时,觉得之前学的不深。下课后仔细总结了一下。自己写了数字塔代码,下面程序中的Third和Fourth类中。拉勾IT课小编为大家举例,把这个数字塔列出来。

1 public class Digital_tower {

2 public static void main(String[] args) {

3 First simple_text = new First();

4 System.out.println("————————————————————(我是分割线)");

5 Third advanced_text = new Third(1);

6 System.out.println();

7 System.out.println("————————————————————(我是分割线)");

8 Fourth more_advancedtext = new Fourth(1);

9 }

10 }

11 class First{

12 int a=9;

13 public First() {

14 toSecond();

15 }

16 public void toSecond() {

17 if(a<10) {

18 System.out.println("先运行First");

19 Second skip = new Second();

20 }

21 System.out.println("再次回到First");

22 }

23 }

24 class Second{

25 public Second() {

26 getFirst();

27 }

28 public void getFirst() {

29 System.out.println("后运行Second");

30 }

31 }

32 class Third{

33 public Third() {

34

35 }

36 public Third(int a) {

37 line(a);

38 }

39 public void line(int a) {

40 if(a<10) {

41 line(a+1);

42 }

43 System.out.print(String.format("%3d", a));

44 }

45 }

46 class Fourth{

47 int b=9;

48 public Fourth() {

49

50 }

51 public Fourth(int a){

52 double_line(a,b);

53 }

54 public void double_line(int a,int b) {

55 System.out.print(String.format("%3d", a));

56 if(a<10) {

57 double_line(a+1,b);

58 System.out.print(String.format("%3d", a));

59 }

60 }

61 }

代码运行结果如下

前两个肯定很好理解,First类中的toSecond方法没有运行完,Second中的getFirst方法运行完后一定会回到First的toSecond类中继续执行接下来的代码。

那么Third和Fourth中的代码也是一样的道理。

Third中:if语句,让第一次运行Third的程序先阻塞,开始运行第二次Third程序,这样一直执行下去,当执行到最后一次时,不满足if的条件,开始输出此时的a值,然后该次Third程序执行完毕,回到上一个Third程序,输出上一次的a值。。。直到第一次执行Third程序,输出a=1。

那么Fourth类中的程序,跟Third程序运行一样,没什么区别。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值