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 教师闺蜜祝福语简短