下面是一個示例代碼,用for循環打印一個菱形:
public class PrintDiamond {
public static void main(String[] args) {
int n = 5; // 菱形的行數,這里設定為5行
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();
}
for (int i = n - 1; i >= 1; 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();
}
}
}
運行上面的代碼,將輸出一個菱形:
*
***
*****
*******
*********
*******
*****
***
*