Вот несколько способов создания шаблона пирамиды в Java:
Метод 1. Использование вложенных циклов
public class PyramidPattern {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
Метод 2: использование одного цикла
public class PyramidPattern {
public static void main(String[] args) {
int rows = 5;
int spaces = rows - 1;
int stars = 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= spaces; j++) {
System.out.print(" ");
}
for (int k = 1; k <= stars; k++) {
System.out.print("*");
}
System.out.println();
spaces--;
stars += 2;
}
}
}
Метод 3. Использование рекурсии
public class PyramidPattern {
public static void main(String[] args) {
int rows = 5;
printPyramid(rows, 1, 1);
}
public static void printPyramid(int rows, int currentRow, int stars) {
if (currentRow > rows) {
return;
}
for (int i = 1; i <= rows - currentRow; i++) {
System.out.print(" ");
}
for (int j = 1; j <= stars; j++) {
System.out.print("*");
}
System.out.println();
printPyramid(rows, currentRow + 1, stars + 2);
}
}