可以通过先打印三角形再打印倒三角形来打印菱形。一个例子如下:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
演示此过程的程序如下。
public class Example { public static void main(String[] args) { int n = 6; int s = n - 1; System.out.print("A diamond with " + 2*n + " rows is as follows:\n\n"); for (int i = 0; i < n; i++) { for (int j = 0; j < s; j++) System.out.print(" "); for (int j = 0; j <= i; j++) System.out.print("* "); System.out.print("\n"); s--; } s = 0; for (int i = n; i > 0; i--) { for (int j = 0; j < s; j++) System.out.print(" "); for (int j = 0; j < i; j++) System.out.print("* "); System.out.print("\n"); s++; } } }
输出结果
一个有12行的钻石如下所示: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
现在让我们了解上面的程序。
钻石形状是通过先打印三角形然后再打印倒三角形来创建的。这是通过使用嵌套的for循环来完成的。上方三角形的代码段如下所示。
int n = 6; int s = n - 1; System.out.print("A diamond with " + 2*n + " rows is as follows:\n\n"); for (int i = 0; i < n; i++) { for (int j = 0; j < s; j++) System.out.print(" "); for (int j = 0; j <= i; j++) System.out.print("* "); System.out.print("\n"); s--; }
倒置的下三角形的代码段如下所示。
s = 0; for (int i = n; i > 0; i--) { for (int j = 0; j < s; j++) System.out.print(" "); for (int j = 0; j < i; j++) System.out.print("* "); System.out.print("\n"); s++; }