Подсказка: вы должны знать количество символов в каждой строке.Также обратите внимание, где находится индекс "*".Вы также должны разделить алмаз на верхнюю и нижнюю половинки.Затем сделайте цикл из этого знания, что до и после "*" есть "/" или "\", а число "/" или "\" будет увеличиваться после каждого цикла.
Вот пример кода.
/**
*
*
*/
public class Diamond {
public static void main(String[] args) {
int diamondHeight = 18;
int diamondWidth = 21;
String header = "";
header = makeDiamondTemplate(diamondWidth, '+', '-', '-', '-');
System.out.println(header);
makeUpperHalf(diamondHeight / 2, diamondWidth);
makeLowerHalf(diamondHeight / 2, diamondWidth);
System.out.println(header);
makeLowerHalf(diamondHeight / 2, diamondWidth);
makeUpperHalf(diamondHeight / 2, diamondWidth);
System.out.println(header);
}
public static String makeDiamondTemplate(int diamondWidth, char border, char mid, char fillerLeft,
char fillerRight) {
String result = "" + border;
int midIndex = diamondWidth / 2;
for (int i = 1; i < diamondWidth - 1; i++) {
if (midIndex == i) {
result = result + mid;
} else if (i < midIndex) {
result = result + fillerLeft;
} else if (i > midIndex) {
result = result + fillerRight;
}
}
result = result + border;
return result;
}
public static void makeUpperHalf(int diamondHeight, int diamondWidth) {
StringBuilder template = new StringBuilder(makeDiamondTemplate(diamondWidth, '|', '*', ' ', ' '));
int starIndex = diamondWidth / 2;
System.out.println(template);
for (int i = 1; i < diamondHeight; i++) {
template.setCharAt(starIndex - i, '/');
template.setCharAt(starIndex + i, '\\');
System.out.println(template);
}
}
public static void makeLowerHalf(int diamondHeight, int diamondWidth) {
StringBuilder template = new StringBuilder(makeDiamondTemplate(diamondWidth, '|', '*', '\\', '/'));
int starIndex = diamondWidth / 2;
int replaceStart = starIndex - 2;
if (template.length() > 1) {
template.setCharAt(1, ' ');
template.setCharAt(template.length() - 2, ' ');
}
System.out.println(template);
for (int i = 1; i < diamondHeight; i++) {
template.setCharAt(starIndex - replaceStart, ' ');
template.setCharAt(starIndex + replaceStart, ' ');
replaceStart--;
System.out.println(template);
}
}
}