How to write code in Java to print a diamond shape?.
Here is a Java code example for printing a diamond shape:
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;
}
}
}
After running the program, you will be prompted to enter the number of rows for the diamond. Once you input the number, the corresponding diamond pattern will be printed.