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 父母生日祝福语 简短独特