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列印出來
有很多值得學習的地方:
- for迴圈中引入char,簡便易懂。以後可以利用起來
- 充分利用陣列特性,先將陣列所有元素代替為" ",再找每個字母在陣列中位置的關係來填充陣列,簡單明瞭,易於理解,nice code!