How to make a triangle with a nested for

2020-05-11 10:10发布

I need to use a nested for loop in Java to make a triangle like this

********
 *******
  ******
   *****
    ****
     ***
      **
       *

Heres my code:

 for (int i=8; i>0; i--)
  {
  for (int j=0; j<i; j++)
  {
      System.out.print('#');
    }
    System.out.println("");
}

I get a triangle but not the one i want. Instead, my triangle looks like this:

********
*******
******
*****
****
***
**
*

3条回答
戒情不戒烟
2楼-- · 2020-05-11 10:58

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.

查看更多
贪生不怕死
3楼-- · 2020-05-11 10:58

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.

查看更多
▲ chillily
4楼-- · 2020-05-11 11:08

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();
    }
}
查看更多
登录 后发表回答