在JavaScript课上,老师要求我们打印空心菱形,有位同学的思路很独特,我简单修改了一下,在这里分享出来。
package important;
public class PrintHollowDiamond {
public static String p(int x, int y, int center) {
//当x、y轴大于对称轴时,对cneter取模
if (x > center)
// x = 2 * center - x;
x = x % center;
if (y > center)
// y = 2 * center - y;
y = y % center;
//如果x+y等于对称轴,则返回"*"
if (x + y == center)
return "*";
return "-";
}
public static void main(String[] args) {
int line = 3;
int n = 2 * line - 1; //构建一个n行*n行的坐标系
int center = line - 1; //x轴和y轴的对称轴
/**
* center在这里为2,也就是菱形关于x=2和y=2对称
*
* 0 1 2 3 4 x轴
* - - - - -
* 0| *
* 1| * *
* 2|* *
* 3| * *
* 4| *
* y
* 轴
*/
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
System.out.print(p(x, y, center));
}
System.out.println();
}
}
}