使用嵌套for循环创建三角形时,如何在各个字符之间放置空格?

时间:2017-03-27 23:08:17

标签: java nested-loops

如果这个问题重复,我很抱歉,但我没有看到这个特定问题的具体答案。

我试图在我在下面的代码中使用嵌套for循环创建的三角形中的每个单独字符之间放置空格。

    for (int i = 1; i <= 5; i++) {
        for (int j = 5; j >= 1; j--) {
            if (j > i)
                System.out.print(" ");
            else
                System.out.print(j);
        }
        System.out.println();
    }
    System.out.println();

    for (int i = 1; i <= 6; i++) {
        for (int j = 1; j < i; j++) {
            System.out.print(" ");
        }
        for (int j = 1; j <= (5 - i + 1); j++) {
            System.out.print(j);
        }
        System.out.println();
    }

输出:

    1
   21
  321
 4321
54321

12345
 1234
  123
   12
    1 

但是,必须是:

        1

      2 1

    3 2 1

  4 3 2 1

5 4 3 2 1


1 2 3 4 5

  1 2 3 4

    1 2 3

      1 2

        1

我已经尝试将" "放在print语句的两个方面以及两个方面,就像我对这两个三角形的反面一样,无济于事。我错过了什么吗?

2 个答案:

答案 0 :(得分:0)

您也可以尝试这样的事情。

    int spaces=10;
    int z;
    for (int i = 1; i <=5 ; i++) {
        spaces=spaces-2;
        for (int j = 0; j<=spaces ; j++) {
            if(j!=spaces)
                System.out.print(" ");
            else {
                z=i;
                while (z >= 1) {
                    System.out.print(z + " ");
                    z--;
                }
            }
        }
        System.out.println("\n");
    }
    System.out.println("\n");
    spaces=-2;
    int m;
    for (int i = 1; i <=5 ; i++) {
        spaces=spaces+2;
        for (int j = 0; j <=spaces ; j++) {
            if(j!=spaces)
                System.out.print(" ");
            else{
                z=i;
                m=1;
                while (m<=6-z) {
                    System.out.print(m + " ");
                    m++;
                }
            }
        }
        System.out.println("\n");
    }

答案 1 :(得分:-1)

只需将System.out.print(j);更改为System.out.print(j + " ");

即可