Java程序打印钻石形状
可以通过先打印三角形再打印倒三角形来打印菱形。一个例子如下:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
演示此过程的程序如下。
示例
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++;
}热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短