如何在java中使用for循环打印带有"*"的三角形?

Ber*_*mas -1 java for-loop console-output

我想用for循环绘制一个像下面这样的星形的三角形,但我真的不知道怎么做这个?三角形将是这样的:

*
**
***
****
*****
******
*******
********
*********
**********
Run Code Online (Sandbox Code Playgroud)

等等.有人可以帮帮我吗?

public class Project1 {
    public static void main (String[] args){
        int c, d, e;
        for (c = 1 ; c <= 8 ; c++){
            for (d = 1 ; d <= c ; d++){
                System.out.print ("*");
            }
            System.out.println("");
        }

        for (e = 1 ; e <= 4 ; e++){
            System.out.println ("***");
        }
    } 
} 
Run Code Online (Sandbox Code Playgroud)

这是我从互联网上找到的,但我不明白为什么它使用两个循环.(我理解用于构建茎的那个.)

Ale*_*x W 5

public static void main(String[] args)
{

    StringBuilder stars = new StringBuilder();

    for(int i = 0; i <= 10; i++)
    {
           stars.append("*");
           System.out.println(stars);
    }

}
Run Code Online (Sandbox Code Playgroud)

或者使用嵌套循环:(这是练习真正试图让你做的)

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1使用字符串连接的巧妙方法.我没想过:( (2认同)
  • @Mahesh其实不那么聪明.像这样的大量串联将更好地被字符串构建者使用. (2认同)