java输出菱形

java 控制台输出菱

在群里看到了一个这样的题目在这里插入图片描述

思路

了解菱形如何画出,我是用的是画上半边,之后画下半边
寻找菱形的规律 使用递归得到上半边为x时,菱形的个数
通过输入的和while循环的菱形个数对比,得到递归了几次,此时递归的次数就是上半层的层数
得到上班层层数,就可以画菱形了

public class tttttttttest {
	private static int x = 0;

	public static void main(String[] args) throws MalformedURLException, IOException {
		Scanner input = new Scanner(System.in);
		System.out.println("请输入数字");

		int str = input.nextInt();
		JSONObject json = bb(str);
		int up = json.getIntValue("up");
		System.out.println("剩余的*:" + json.getIntValue("remainder"));

		for (int i = 0; i <= up; i++) {
			for (int j = 0; j < up - i; j++) {
				System.out.print(" ");
			}
			for (int k = 1; k <= 2 * i - 1; k++) {
				System.out.print("*");
			}
			System.out.println();
		}
		for (int i = up - 1; i > 0; i--) {
			for (int j = 0; j < up - i; j++) {
				System.out.print(" ");
			}
			for (int k = 1; k <= 2 * i - 1; k++) {
				System.out.print("*");
			}
			System.out.println();
		}

	}
	public static JSONObject bb(int str) {
		int count = 1;
		JSONObject json = new JSONObject();

		while (true) {
			int c = f(count);
			if (c > str) {
				json.put("remainder", str - f(count - 1)); // 多余的
				json.put("up", count - 1); // 上半层
				return json;
			}
			count++;

		}
	}
	public static Integer f(int o) {
		if (o == 1) {
			return 1;
		}
		return f(o - 1) + 4 * (o - 1);

	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值