当前位置: 代码迷 >> 综合 >> exercism————Diamonds
  详细解决方案

exercism————Diamonds

热度:69   发布时间:2023-12-13 18:11:09.0

题目:

在这里插入图片描述

方法一:

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 partfor (int i = 0; i <= times; i++) {
    // print spacesfor (int j = 0; j < (times - i); j++) {
    System.out.print(" ");}// print lettersSystem.out.print(ALPHABET[i]);// print spacesfor (int j = 0; j < (2 * i - 1); j++) {
    System.out.print(" ");}// print lettersif (i == 0) {
     System.out.println();}else {
    System.out.println(ALPHABET[i]);}}// The bottom half of partfor (int i = 0; i < times; i++) {
    // print spacesfor (int j = 0; j < (i + 1); j++) {
    System.out.print(" ");}// print lettersSystem.out.print(ALPHABET[times - i - 1]);// print spacesfor (int j = 0; j < (2 * (times - i) - 3); j++) {
    System.out.print(" ");}// print lettersif (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!