Java小程序之輸出星號

題目:打印出以下圖案(菱形) 
    * 
   *** 
 ****** 
******** 
 ****** 
  *** 
   * c++

編程工具使用eclipse編程

代碼以下:eclipse

package test;

public class starsList {
    public int totaLines = 0; // 最大行數

    public static void main(String [] args){
        starsList aaa = new starsList();
        aaa.setNum(17,17);// 第一個是要顯示的行數。第二個是總行數
    }

    // 單行星號打印(空格和星號)
    public void prints(int num,int totals){
        String string = "";
        int lang = totals-num>=0 ? num : num-(num-totals)*2;
        
        for(int a=0;a<lang;a++){
            string +="*";
        }
        
        int space = (totals-lang)/2;
        for(int b=0;b<space;b++){
            string = " "+string;
            string = string+" ";
        }
        
        System.out.println(string);
        System.out.println('\n');
    }
    // 根據打印行數計算每行星號個數並調用單行打印
    public void setNum(int lines,int totals2){
        if(lines>totals2){
            System.out.println("要顯示的行數("+lines+") 大於總行數("+totals2+")");
            return;
        }
        starsList bb = new starsList();
        for(int c = 0;c<lines;c++){
            int n = (2*c)+1;
            bb.prints(n,totals2);
        }
    }
}
相關文章
相關標籤/搜索