How to make a triangle with a nested for

北战南征 提交于 2019-12-02 23:54:57

问题


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:

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

回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/23688955/how-to-make-a-triangle-with-a-nested-for

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