以下是一个打印菱形的Java代码示例:
import java.util.Scanner;
public class DiamondPattern {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入菱形的行数:");
int rows = scanner.nextInt();
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 j = 1; j <= stars; j++) {
System.out.print("*");
}
System.out.println();
spaces--;
stars += 2;
}
// 打印下半部分
spaces = 1;
stars = rows * 2 - 3;
for (int i = 1; i <= rows - 1; i++) {
for (int j = 1; j <= spaces; j++) {
System.out.print(" ");
}
for (int j = 1; j <= stars; j++) {
System.out.print("*");
}
System.out.println();
spaces++;
stars -= 2;
}
}
}
运行程序后,会提示输入菱形的行数,输入后即可打印出对应行数的菱形图案。