How can i print a triangle with “*”s using for loop in java?

前端 未结 9 974
情话喂你
情话喂你 2021-01-29 10:35

I want to draw a triangle with stars like below using for loop, but i really don\'t have any idea of how to do this ? Triangle is going to be like this:

*
**
**         


        
9条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-29 11:06

    public static void main(String[] args)
    {
    
        StringBuilder stars = new StringBuilder();
    
        for(int i = 0; i <= 10; i++)
        {
               stars.append("*");
               System.out.println(stars);
        }
    
    }
    

    Or alternatively using nested loops: (This is what the exercise was really trying to get you to do)

    public static void main(String[] args)
    {
        for(int i = 0; i <= 10; i++)
        {
            for(int j=0; j<=i; j++)
            {
                System.out.print("*");
            }
            System.out.print("\n");
        }
    }
    

提交回复
热议问题