exercism————Diamonds

题目:

在这里插入图片描述

方法一:

static final char[] ALPHABET = {'A','B','C','D','E','F','G','H','I','G','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

	public void printDimond(char letter) {
		if (!alphabetContains(letter)) {throw new InputMismatchException("Invalid input");}
		int times = cycleTimes(letter);
		// The top half of part
		for (int i = 0; i <= times; i++) {
			// print spaces
			for (int j = 0; j < (times - i); j++) {
				System.out.print(" ");
			}
			// print letters
			System.out.print(ALPHABET[i]);
			// print spaces
			for (int j = 0; j < (2 * i - 1); j++) {
				System.out.print(" ");
			}
			// print letters
			if (i == 0) { System.out.println();}
			else {System.out.println(ALPHABET[i]);}
		}

		// The bottom half of part
		for (int i = 0; i < times; i++) {
			// print spaces
			for (int j = 0; j < (i + 1); j++) {
				System.out.print(" ");
			}
			// print letters
			System.out.print(ALPHABET[times - i - 1]);
			// print spaces
			for (int j = 0; j < (2 * (times - i) - 3); j++) {
				System.out.print(" ");
			}
			// print letters
			if (i == (times - 1)) { System.out.println(); }
			else { System.out.println(ALPHABET[times - i - 1]); }

方法二:


	private static final char START_CHAR = 'A';

	 List<String> printToList(char endChar) {

		List<String> result = new ArrayList<>();

		for (char c = START_CHAR; c < endChar; c++) {
			result.add(getLine(c, endChar));
		}

		for (char c = endChar; c >= START_CHAR; c--) {
			result.add(getLine(c, endChar));
		}

		return result;
	}

	private String getLine(char c, char endChar) {
		int lineLength = (endChar - START_CHAR) * 2 + 1;

		char[] line = new char[lineLength];
		for (int i = 0; i < lineLength; i++) {
			line[i] = ' ';
		}

		line[endChar - c] = c;
		line[endChar + c - 2 * START_CHAR] = c;

		return String.valueOf(line);
	}

Conclusion:

方法一:运用大量for循环,代码可读性较差
方法二:思路奇特,通过把每行储存在List中,最后用Iterator打印出来
有很多值得学习的地方:

  1. for循环中引入char,简便易懂。以后可以利用起来
  2. 充分利用数组特性,先将数组所有元素代替为" ",再找每个字母在数组中位置的关系来填充数组,简单明了,易于理解,nice code!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值