java|JAVA 打印菱形








1.任意菱形

//菱形 Scanner myscanner = new Scanner(System.in); int n = myscanner.nextInt(); for (int i = 0; i < n / 2 + 1; i++) {//控制行数 for (int j = 0; j < n / 2 - i; j++) {//打印空格 System.out.print(" "); } for (int k = 0; k < 2 * i +1; k++) {//打印* System.out.print("*"); } System.out.println("\n"); } for (int i = 1; i < n / 2 + 1; i++) { for (int j = 0; j < i; j++) { System.out.print(" "); } for (int k = 2 * (n / 2 - i) + 1; k > 0; k--) { System.out.print("*"); } System.out.println("\n"); }

【java|JAVA 打印菱形】java|JAVA 打印菱形
文章图片

2.空心菱形
方法1
int n; Scanner myscanner = new Scanner(System.in); n = myscanner.nextInt(); for (int i = 0; i < n / 2 + 1; i++) {//控制行数 for (int j = 0; j < n / 2 + 1 - i; j++) { System.out.printf(" "); } for (int k = 0; k < 2 * i + 1; k++) { if (k == 0 || k == 2 * i){//输出第一颗和最后一颗* System.out.printf("*"); }else System.out.printf(" "); } System.out.printf("\n"); //控制换行 }for (int i = n / 2; i >= 0 ; i--) { for (int j = n / 2 - i + 1; j > 0 ; j--) { System.out.printf(" "); } for (int k = 0; k < 2 * i + 1; k++) { if (k == 0 || k == 2 * i){//输出第一颗和最后一颗* System.out.printf("*"); }else System.out.printf(" "); } System.out.printf("\n"); }

方法2
Scanner myscanner = new Scanner(System.in); int n = myscanner.nextInt(); for (int i = -n; i <= n; i++) { for (int j = -n; j <= n; j++) { int k = Math.abs(i) + Math.abs(j); if (k == n){ System.out.printf("*"); }else { System.out.printf(" "); } } System.out.println("\n"); }



java|JAVA 打印菱形
文章图片

3.边框菱形
Scanner myscanner = new Scanner(System.in); int n = myscanner.nextInt(); for (int i = -n; i <= n; i++) { for (int j = -n; j <= n; j++) { int k = Math.abs(i) + Math.abs(j); if (k >= n){ System.out.printf("*"); }else { System.out.printf(" "); } } System.out.println("\n"); }

java|JAVA 打印菱形
文章图片

4.数字菱形
Scanner myscanner = new Scanner(System.in); int n = myscanner.nextInt(); for (int i = 0; i < n; i++) { int k = 1; int j; for (j = 0; j < Math.abs(n / 2 -i); j++) { System.out.printf(" "); } for ( j = 0; j < n - 2 * Math.abs(n / 2 - i); j++) { System.out.print(k); if (j < n / 2 - Math.abs(n / 2 -i)){ k++; }else { k--; } } System.out.println("\t"); }

java|JAVA 打印菱形
文章图片


    推荐阅读