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 生日开业蛋糕祝福语简短