打印正菱形
public class Graphics { public static void main(String[] args) { new Graphics().paint(9, false); } /** * 打印正菱形 * @param h 高度 * @param hollow 是否空心 */ public void paint(int h, boolean hollow){ if(h%2 != 1){ System.out.println("the height number cannot be even-number"); return; } h = h/2; for (int i = -h; i <= h; i++) { //取绝对值 int n = Math.abs(i); /* 打印空白部分 变量变化趋势为 n-1 n-2..1 0 1 .. n-2 n-1 */ for (int j = 0; j < n; j++) { System.out.print(" "); } /* 打印*号部分 变量变化趋势 1 2 .. n .. 2 1 */ for (int j = (h-n)*2+1; j > 0 ; j--) { if(hollow && j != ((h-n)*2+1) && j != 1){ System.out.print(" "); }else{ System.out.print(" * "); } } System.out.println(); } } }
输出结果