java输出打印空心菱形
第一反应:分上下两块,找规律分别输出左边和中间的空格
for (int row
=0;row
<=3;row
++){
for (int space
=0;space
<3-row
;space
++) System
.out
.print(" ");
System
.out
.print("*");
for (int center
=0;center
<row
*2-1;center
++) System
.out
.print(" ");
System
.out
.println(row
==0?" ":"*");
}
for (int row
=2;row
>=0;row
--){
for (int space
=0;space
<3-row
;space
++) System
.out
.print(" ");
System
.out
.print("*");
for (int center
=0; center
<row
*2-1;center
++) System
.out
.print(" ");
System
.out
.println(row
==0?" ":"*");
}
结果 。
网上找到的觉得的更巧妙的解法:按位置分布打印"*“或” "
自己的理解: 外层for循环行数,内层嵌套两个列数的for循环; 当(行数=列数) 或 (行数+列数=8)时输出"*",否则输出" "
for (int row
=0;row
<8;row
++){
for(int column
=4;column
>0;column
--)
System
.out
.print(row
==column
||row
+column
==8?"*":" ");
for(int column
=2;column
<5;column
++)
System
.out
.print(row
==column
||row
+column
==8?"*":" ");
System
.out
.println();
}
结果