列印數字塔中涉及到的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代碼時,也可以這樣寫,減少代碼量,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/168437.html
標籤:Java
