阅读量:0
下面是一个示例代码,用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(); } } }
运行上面的代码,将输出一个菱形:
* *** ***** ******* ********* ******* ***** *** *