打印数字塔中涉及到的Java知识
数据结构课上,老师讲的数字塔时,觉得之前学的不深。下课后仔细总结了一下。自己写了数字塔代码,下面程序中的Third和Fourth类中。
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程序运行一样,没什么区别。
以后写相关的Java代码时,也可以这样写,减少代码量。