2014-02-23 57 views
-2

我想打印這種模式,但我無法得到打印*在最後幾行計劃空心三角:*模式

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

但我結束了這一點,最後一行是問題

     * 
        *  * 
       *     * 
      *       * 
    *         * 

for (int i = 1; i <= m; i++) { 
    for (int j = 1; j <= m - i; j++) { 
     System.out.print(" "); 
    } 
    for (int k = 1; k < i; k++) { 
     if (k == 1 || k == i - 1) 
      System.out.print("*"); 
     System.out.print(" "); 
    } 
    System.out.println(" "); 
} 

回答

1

你幾乎在那裏。你只需要包括條件寫*如果k處理最後一排,換句話說i == m所以你

if (k == 1 || k == i - 1) 

應該看起來更像

if (k == 1 || k == i - 1 || i == m) 

另一件事是,你需要保證,不管您打印*或不,必須將兩個字符添加到行,這意味着"* "" "。目前您只打印"*"" "這不是您想要的。更改

if (k == 1 || k == i - 1 || i == m) 
    System.out.print("*"); 
System.out.print(" "); 

if (k == 1 || k == i - 1 || i == m) 
    System.out.print("*"); 
else 
    System.out.print(" "); 
System.out.print(" "); 

也許簡單

if (k == 1 || k == i - 1 || i == m) 
    System.out.print("* "); 
else 
    System.out.print(" "); 
0
 import java.util.*; 
     import java.awt.*; 
     class Spiral 
      { 
     public static void main(String[] args) 
       {  
      int m=12; 
      for (int i = 1; i <= m; i++) { 
       for (int j = 1; j <= m - i; j++) 
       { 
       System.out.print(" "); 
       } 
      for (int k = 1; k < i; k++) { 
      if (k == 1 || k == i-1) 
      System.out.print("*"); 

      System.out.print(" "); 
       if(i==m) 
       { 
      for(int n=2;n<12;n++) 
       { 
      System.out.print("*"); 
      System.out.print(" "); 

      break; 
       } 
      } 
     System.out.println(" "); 
     } 

     } 
    } 

enter image description here