题目:
解法一:
package exercism;import java.util.InputMismatchException;public class Diamond {
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]); }}}boolean alphabetContains(char c) {
for (char e:ALPHABET) {
if (e == c) {
return true;}}return false;
}int cycleTimes(char c) {
int times = 0;for (int i = 0; i < ALPHABET.length; i++) {
if (c == ALPHABET[i]) {
times = i;}}return times;}}
解法二:
import java.util.Arrays;
import java.util.List;public class DiamondPrinter {
public List<String> printToList(char letter) {
int number = letter - 'A' + 1;int size = 2 * (number - 1) + 1;String[] lines = new String[size];for (int i=0; i<size / 2 + 1; i++) {
char c = (char) ('A' + i);int leftPosition = size / 2 + 1 - i - 1;int rightPosition = size - leftPosition - 1;char[] buffer = new char[size];Arrays.fill(buffer, ' ');buffer[leftPosition] = c;buffer[rightPosition] = c;String line = new String(buffer);lines[i] = line;lines[size - 1 - i] = line;}return Arrays.asList(lines);}}
解法三:
import java.util.ArrayList;
import java.util.List;class DiamondPrinter {
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);}
}