for迴圈輸出樹木的形狀【java】

來源:互聯網
上載者:User

標籤:分析   main   print   star   alt   換行   迴圈   i++   out   

使用for迴圈語句輸出以下“樹木”效果:

    *   ***  ***** ****************    *    *    *    *    *

代碼:

/*    *   ***  ***** ****************    *    *    *    *    *分析:    - 樹頂(共5層)        每層構成:每層每層空格數+每層星星數            第1層 -- 空格數:4 + 星星數:1            第2層 -- 空格數:3 + 星星數:3            第3層 -- 空格數:2 + 星星數:4            第4層 -- 空格數:1 + 星星數:7            第5層 -- 空格數:0 + 星星數:9                        分析:            第1層 -- 空格數:4(= 5-1) + 星星數:1(= 2*1-1)            第2層 -- 空格數:3(= 5-2) + 星星數:3(= 2*2-1)            第3層 -- 空格數:2(= 5-3) + 星星數:4(= 2*3-1)            第4層 -- 空格數:1(= 5-4) + 星星數:7(= 2*4-1)            第5層 -- 空格數:0(= 5-5) + 星星數:9(= 2*5-1)            推理:(共layer層樹頂)            第i層 -- 空格數 = (layer-i) + (星星數 = 2*i-1)    - 樹榦(共5層)            第1層 -- 空格數:4 + 星星數:1            第2層 -- 空格數:4 + 星星數:1            第3層 -- 空格數:4 + 星星數:1            第4層 -- 空格數:4 + 星星數:1            第5層 -- 空格數:4 + 星星數:1            相似於第1層結果,即:            第1層 -- 空格數:4 + 星星數:1            類比樹頂第i層結果得出:第1層 -- 空格數:(layer-1)+ 星星數:1            分析:(共layer層樹頂)            第1層 -- 空格數:(layer-1)+ 星星數:1            第2層 -- 空格數:(layer-1)+ 星星數:1            第3層 -- 空格數:(layer-1)+ 星星數:1            第4層 -- 空格數:(layer-1)+ 星星數:1            第5層 -- 空格數:(layer-1)+ 星星數:1*/public class StarTree{    public static void main(String[] args){        int layer = 5;        // 一、樹頂        for(int i=1;i<=layer;i++){                         // 1、擷取空格需要顯示數量            int spaceNum = layer-i;             for(int j=1;j<=spaceNum;j++){  // 需要列印空格的數量                System.out.print(" ");            }                        // 2、擷取星星需要顯示的數量            int starNum = 2*i-1;            for(int j=1;j<=starNum;j++){ // 需要列印星星的數量                System.out.print("*");            }            // 3、換行            System.out.println();        }                // 二、樹榦        for(int i=1;i<=layer;i++){            // 1、擷取空格需要顯示數量            int spaceNum = layer-1;            for(int j=1;j<=spaceNum;j++){                System.out.print(" ");            }            // 2、擷取星星需要顯示的數量並換行            System.out.println("*");        }    }}

 代碼結果顯示:

 

for迴圈輸出樹木的形狀【java】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.