2015-06-09 75 views
5

我正在嘗試使用for循環和嵌套for循環來製作聖誕樹。對於我來說,我需要能夠用*製作金字塔。我已經嘗試了無數次,並且在製作一個時遇到了問題。這裏是我的代碼:使用for循環創建聖誕樹

for(int i=1;i<=10;i++){ 
    for(int j=10;j>i;j--){ 
     System.out.println(" "); 
    } 

    for(int k=1;k<=i;k++){ 
     System.out.print("*"); 
    } 

    for(int l=10;l<=1;l++){ 
     for(int h=1;h<=10;h++){ 
      System.out.print(" "); 
     } 
    } 

    System.out.println(); 
} 

我所試圖做的是:

 * 
    *** 
    ***** 
    ******* 
+1

出寫邏輯上的紙peice的。 –

回答

6

試試這個簡單得多代碼:

public class ChristmasTree { 

public static void main(String[] args) { 

    for (int i = 0; i < 10; i++) { 
    for (int j = 0; j < 10 - i; j++) 
    System.out.print(" "); 
    for (int k = 0; k < (2 * i + 1); k++) 
    System.out.print("*"); 
    System.out.println(); 
    } 
} 
} 

它使用3個循環:

  • 第一個爲行數,
  • 第二個用於打印空格,
  • 第三個用於打印星號。
+0

感謝它的工作。你能解釋爲什麼你做了2 * i + 1 –

+0

第一次迭代((2 * 0)+1)= 1星。第二次迭代((2 * 1)+1)= 3星。第三次迭代((2 * 2)+1)= 5星等。 – mcw

+0

參見第1行有1星。第2有3,第3有5。因此它遵循2 *(n-1)+1的一般規則。因爲我們從0開始,所以(n-1)= i。因此,第(i + 1)行中的星數= 2 * i + 1。上面的程序打印聖誕樹上的 –

7

你可以用簡單的邏輯去做

for (int i = 0; i < 4; i++) 
      System.out.println(" *******".substring(i, 4 + 2*i)); 
0
public class Stars { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     Scanner s=new Scanner(System.in); 
     System.out.println("Enter Row/Column Value::"); 
     int i,j,k,n; 
     n=s.nextInt(); 
     for(i=1; i<n; i++){ 
      for(j=n+(n/2); j>i; j--){ 
       System.out.print(" ");} 
      for(k=1; k<=2*i-1; k++){ 
       System.out.print("*");} 
      System.out.println(""); 
      } 
     for(i=1; i<n+(n/2); i++){ 
      for(j=n+(n/2); j>i; j--){ 
       System.out.print(" ");} 
      for(k=1; k<=2*i-1; k++){ 
       System.out.print("*");} 
      System.out.println(""); 
     } 
      for(i=1; i<n-(n/2); i++){ 
      for(j=n+(n/2); j>1; j--){ 
       System.out.print(" ");} 
      for(k=n/2; k<=(n/2)+1; k++){ 
       System.out.print("*");} 
      System.out.println(""); 
     } 
    } 
} 
+0

。 –

+3

雖然此代碼可能會回答問題,但提供有關如何解決問題和/或爲何解決問題的其他上下文可以提高答案的長期價值。 –

-1
import java.util.Scanner; 

public class cmastree{ 

    public static void main (String[]args){ 
     Scanner keyboard=new Scanner (System.in); 

     int j; 
     System.out.println ("Enter a number"); 
     j=keyboard.nextInt(); 
     /*take the above part out and change the j variable if you want to set 
     the size*/ 
     for(int i=1; i<=j; i+=2){ 
      int numSpaces = (j-i)/2; 
     for (int k=0; k<numSpaces; k++){ 
      System.out.print(" "); 
      } 
     for(int k=0; k<numSpaces; k++){ 
      System.out.print("*"); 
      } 
      System.out.println(); 
     } 
    } 
}