如何做一个嵌套的三角形 [英] How to make a triangle with a nested for

查看:240
本文介绍了如何做一个嵌套的三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  *******在Java中我需要使用一个嵌套for循环* 
*******
******
*****
****
***
**
*

继承我的代码:


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

我得到一个三角形,但不是我想要的。相反,我的三角形看起来像这样:

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


解决方案

使用以下代码
$ b $ (int i = f; i> 0; i - ){

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



$ b $ p
$ b

你的代码也在三角形的末尾产生一个不必要的行,代码会照顾到这一行,并能够制作所需的三角形。



我已经测试过了,请参阅 here

I need to use a nested for loop in Java to make a traingle 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:

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

解决方案

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.

这篇关于如何做一个嵌套的三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆