打印如圖所示菱形9行9列(提示可以將菱形分成上下兩個三角形,分析每行空格數和星號個數的關系)
代碼如下:
1 package com.homework.lhh; 2 3 public class Ex20 { 4 public static void main(String[] args) { 5 for(int i = 1; i <= 5; i++){ 6 for(int j = 1; j <= 5 - i; j++){ 7 System.out.print(" "); 8 } 9 for(int j = 1; j <= 2 * i - 1; j++){ 10 System.out.print("*"); 11 } 12 System.out.println(); 13 } 14 for(int i = 4; i > 0; i--){ 15 for(int j = 1; j <= 5 - i; j++){ 16 System.out.print(" "); 17 } 18 for(int j = 1; j <= 2 * i - 1; j++){ 19 System.out.print("*"); 20 } 21 System.out.println(); 22 } 23 } 24 }
運行結果如圖: