2015-05-14 61 views
0

我需要做一個三角形,看起來像這樣如何創建使用循環

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

目前,我有一個工作一個看起來像

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

使用Java中的一個落後的三角形循環:

public static void standard(int n) 
    { 
     for(int x = 1; x <= n; x++) 
     { 
     for(int c = 1; c <= x; c++) 
     { 
      System.out.print("*"); 
     } 
     System.out.println(); 
     } 
    } 

我如何去使這項工作

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

這是我的嘗試:

public static void backward(int n) 
{ 
    for(int x = 7; x <= n; x++) 
    { 
     for(int y = 1; y >= x; y--) 
     { 
      if (x >= y) 
      { 
       System.out.print("*"); 
      } 
      else 
      { 
       System.out.print(""); 
      } 
     } 
     System.out.println(); 
    } 
} 
+1

一個到您的輸出減少填充添加填充每一行......通過填充我的意思是空間。 – brso05

+0

考慮印刷空間以及星號。 – jdv

+0

將++更改爲-1 – 2015-05-14 14:04:55

回答

5

在每一行打印n字符:如果索引c < n - x,打印空間,否則打印星號:

for (int x = 1; x <= n; x++) { 
    for (int c = 0; c < n; c++) 
     System.out.print(c < n - x ? ' ' : '*');  
    System.out.println(); 
} 

輸出(N = 6):

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

+1

謝謝,完美的工作。 – TheJavaDue1234

0
public static void standard(int n) 
    { 
     for(int x = 1; x <= n; x++) 
     { 

新代碼這裏

  for (int b = 0; b <= (n - x); b++) 
      System.out.print(" "); 

這段代碼加星之前添加空格。因爲三角形超過2是矩形,我們知道,總長度爲n每一次,我們只是做了別人的空間,只顯示三角形

  for(int c = 1; c <= x; c++) 
     { 
      System.out.print("*"); 
     } 
     System.out.println(); 
     } 
    } 
0
void triangle(int n) { 

     // create first line 
     StringBuffer out = new StringBuffer(2 * n + 1); 
     for (int i = 0; i < n - 1; ++i) { 
      out.append(' '); 
     } 
     out.append('*'); 

     // repeatedly remove a space and add a star 
     while (n-- > 0) { 
      System.out.println(out); 
      out.deleteCharAt(0); 
      out.append("*"); 
     } 
    } 
0

只要改變循環,使x表示的空間和打印該空格數,然後再打印字符的缺失,以填補行號:

for (int x = n-1; x >= 0; x--) { 
    for (int c = 0; c < x; c++) { 
     System.out.print(" "); 
    } 
    for (int c = x; c < n; c++) { 
     System.out.print("*"); 
    } 
    System.out.println(); 
}