java 经典范例

使用for 循环输出空心菱形

 1 package 开阳;
 2 import java.util.Scanner;
 3 public class image {
 4     public static void main(String[] args){
 5         Scanner scan = new Scanner(System.in);
 6         System.out.println("请输入一个奇数,用来构造一个空心菱形");
 7         int key =scan.nextInt();
 8         System.out.println();
 9         if (key%2==0){
10             System.out.println("您输入的是一个偶数");
11         }
12         else{
13             printHollowRhombus(key);
14         }
15     }
16     public static void printHollowRhombus(int size){        
17         for(int i=1;i<(size+1)/2;i++){
18             for(int j=1;j<=size;j++)
19                 if (Math.abs((size+1)/2-j)==i-1){
20                     System.out.print("*");
21                 }
22                 else{
23                     System.out.print(" ");
24                 }
25             System.out.println();
26             }
27         for(int i=(size+1)/2;i>0;i--){
28             for(int j=1;j<=size;j++){
29                 if (Math.abs((size+1)/2-j)==i-1){
30                     System.out.print("*");
31                 }
32                 else{
33                     System.out.print(" ");
34             }
35             
36             }
37             System.out.println();
38         }
39     }
40 }
原文地址:https://www.cnblogs.com/tester-hehehe/p/5462583.html