java 打印 空心菱形

这篇博客分享了一种使用Java编程打印空心菱形的方法。通过创建PrintHollowDiamond类,利用对称性原理计算坐标,实现了空心菱形的输出。在main方法中,创建了一个n行的坐标系,并通过双重循环打印每个位置的符号,从而形成菱形图案。
摘要由CSDN通过智能技术生成
在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();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值