java编程怎么打出金字塔模式

时间:2025-01-28 09:04:35 网络游戏

在Java中打印金字塔模式可以通过多种方法实现。以下是几种常见的方法:

方法一:使用嵌套循环

```java

public class Pyramid {

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();

}

}

}

```

方法二:使用列表和字符串拼接

```java

public class Pyramid {

public static void main(String[] args) {

int rows = 4;

String[] lines = new String[rows];

for (int r = 0; r < rows; r++) {

int spaceCount = rows - r - 1;

int starCount = 2 * r + 1;

lines[r] = String.format(" %" + spaceCount + "s%s", "", String.format("* %" + starCount + "s", ""));

}

for (String line : lines) {

System.out.println(line);

}

}

}

```

方法三:使用递归

```java

public class Pyramid {

public static void main(String[] args) {

int rows = 5;

printPyramid(rows, 1);

}

public static void printPyramid(int rows, int currentRow) {

if (currentRow > rows) {

return;

}

// 打印空格

for (int i = 1; i <= rows - currentRow; i++) {

System.out.print(" ");

}

// 打印星号

for (int i = 1; i <= 2 * currentRow - 1; i++) {

System.out.print("*");

}

// 换行

System.out.println();

// 递归调用

printPyramid(rows, currentRow + 1);

}

}

```

方法四:使用Scanner输入

```java

import java.util.Scanner;

public class Pyramid {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("请输入金字塔层数: ");

int n = sc.nextInt();

for (int i = 1; i <= n; i++) {

// 打印空格

for (int j = 1; j <= n - i; j++) {

System.out.print(" ");

}

// 打印星号

for (int k = 1; k <= 2 * i - 1; k++) {

System.out.print("*");

}

// 换行

System.out.println();

}

}

}

```

这些方法都可以用来在Java中打印金字塔模式。你可以根据自己的需求和喜好选择合适的方法。