用星星制作三角形

宗尼

我正在尝试制作一个由星星组成三角形的程序,如下所示:

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

我以为自己有它,但是在代码中的某个地方我犯了一个逻辑错误,而不是减少星号之前的空格数量,而是将它们保持在最前面,所以看起来像这样

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

我的代码:

    System.out.print("Give a positive odd integer: ");
    Scanner s = new Scanner(System.in);
    int N = s.nextInt();
    int cnt1 = 0;
    int cnt2 = 0;
    int cnt3 = 0;
    int line = N - 1;
    char c1 = '*';
    char c2 = ' ';
    StringBuilder sb = new StringBuilder();
    if (N > 0 && N % 2 == 1) {
        while (cnt1 < N){
            while (cnt2 < N-line){
                while (cnt3 < line){
                    sb.append(c2);
                    cnt3++;
                }
                sb.append(c1);
                cnt2++;
            }
            line--;
            cnt1++;
            System.out.println(sb.toString());
        }
}
mdnghtblue

您非常接近,您的代码在下面做了一些小修改:(我在循环内移动了几行):

System.out.print("Give a positive odd integer: ");
Scanner s = new Scanner(System.in);
int N = s.nextInt();
int cnt1 = 0;
int line = N - 1;
char c1 = '*';
char c2 = ' ';

if (N > 0 && N % 2 == 1) {
    while (cnt1 < N){
        StringBuilder sb = new StringBuilder(); // CHANGED
        int cnt2 = 0; // CHANGED
        int cnt3 = 0; // CHANGED

        while (cnt2 < N-line){
            while (cnt3 < line){
                sb.append(c2);
                cnt3++;
            }
            sb.append(c1);
            cnt2++;
        }
        line--;
        cnt1++;
        System.out.println(sb.toString());
    }
}

如果输入为7,将打印以下内容:

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

您的问题是某些变量没有被重置。对我来说,红旗是当我看到cnt3变量从未重置为0时,因此它只进入了该循环一次。StringBuilder不重导致这些空间是相同的长度各一次。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章