How to make a triangle with a nested for

允我心安 提交于 2019-12-02 13:45:08

You'll need the outer loop to count the 8 rows. The inner loop would output the *'s for each row. The row count of the outer loop will tell you how many spaces to output versus *'s.

Try this

public static void main(String[] args)
{

    triangle(8);
  }

private static void triangle(int len)
{
    for (int j = 0; j < len; j++)
    {
        for (int k = 0; k < j; k++)
        {
            System.out.print(' ');
        }
        for (int k = len-j; k > 0; k--)
        {
            System.out.print('#');
        }
        System.out.println();
    }
}

Use the following code

int f=8;`
for (int i=f; i>0; i--){

    for (int k=0; k<f-i;k++){
    System.out.print(' ');
    }
    for (int j=0; j<i; j++){
    System.out.print('*');
    }
    if(i-1!=0)System.out.println("");
 }

Your code was also producing an unnecessary line at the end of the triangle, this code takes care of that line and is capable of making the desired triangle.

I have tested it, see here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!