Java数字模式两个三角形并排形成一个正方形/矩形

H_S*_*H_S 2 java loops for-loop numbers

我希望输出看起来像这样:

如何安排这些循环以获得两个三角形编号模式?以及如何改进我的代码。JAVA 中的新功能 :-)

    for (int i = 1; i<=10; i++ ) {
        for (int j = 1; j <= i; j++) {
            System.out.print(j);
        }
        System.out.println();
    }
    for (int count = 1; count <= 10; count++) {
        for (int index=1; index < count+1; index++)
            System.out.print(" ");

        for (int num=10; num >count; num--) {
            System.out.print(num);
        }   
        System.out.println();
    }
Run Code Online (Sandbox Code Playgroud)

Mal*_*alt 5

这样的事情怎么样?

for (int row = 1; row <= 10; row++) {
    for (int j = 1; j <= row; j++) {
        System.out.print(j + " ");
    }
    System.out.print("  ");
    for (int j = 10; j >= row; j--) {
        System.out.print(j + " ");
    }
    System.out.println();
}
Run Code Online (Sandbox Code Playgroud)

输出:

1   10 9 8 7 6 5 4 3 2 1 
1 2   10 9 8 7 6 5 4 3 2 
1 2 3   10 9 8 7 6 5 4 3 
1 2 3 4   10 9 8 7 6 5 4 
1 2 3 4 5   10 9 8 7 6 5 
1 2 3 4 5 6   10 9 8 7 6 
1 2 3 4 5 6 7   10 9 8 7 
1 2 3 4 5 6 7 8   10 9 8 
1 2 3 4 5 6 7 8 9   10 9 
1 2 3 4 5 6 7 8 9 10   10 
Run Code Online (Sandbox Code Playgroud)

解释-在行外循环迭代,所以我改名irow的清晰度。第一个内部循环与您的代码保持不变 - 它负责在对角线之前打印数字。然后我们打印一个双空格 ( System.out.print(" ")),然后第二个循环打印其余的数字,从 10 开始一直到行号。

另一方面,您应该更好地格式化代码。缩进确实有助于提高可读性和理解力。

例如,您的第一个循环如下所示:

  for(int i = 1; i<=10; i++ ) {
    for(int j = 1; j <= i; j++) {
        System.out.print(j);
    }
        System.out.println();
    }
Run Code Online (Sandbox Code Playgroud)

但应该是这样的:

for (int i = 1; i <= 10; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print(j);
    }
    System.out.println();
}
Run Code Online (Sandbox Code Playgroud)

这是相同的代码,但在格式化版本中,更容易看到第二条System.out.println语句跟在内部循环之后,for最后的右括号关闭了外部for循环,而不是其他语句。