问题
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