Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to make a christmas tree using for loops and nested for loops. For me to do that I need to be able to make a pyramids with *. I have tried countless times and I am having problems making one. Here is my code:

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();  
}

What I am trying to do is:

     *
    ***
   *****
  *******
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
198 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this much simpler code:

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();
  }
 }
}

It uses 3 loops:

  • first one for the number of rows,
  • second one for printing the spaces,
  • third one for printing the asterisks.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...