首页 > 代码库 > java打印各种菱形

java打印各种菱形

/**
 * 类说明
 *
 * @author 曾修建
 * @version 创建时间:2014-7-23 上午09:50:46
 */
public class Diamond {

	public static void getDia(int n) {
		System.out.println("第一个 :");
		for (int i = 0; i < n/2+1; i++) {
			for (int j2 = 0; j2 < n/2+1-i; j2++) {
				System.out.print(" ");
			}
			for (int j2 = 0; j2 < 2*i+1; j2++) {
				System.out.print("+");
			}
			System.out.println();
		}

		for (int i = n/2; i > 0; i--) {
			for (int j = 0; j < n/2-i+2; j++) {
				System.out.print(" ");
			}
			for (int j = 0; j < 2*i-1; j++) {
				System.out.print("+");
			}
			System.out.println();
		}
		
		System.out.println("第二个 :");
		for(int i = 1;i <= n;i++){  
		    if(i <= n/2 + 1){  
		        for(int k = 1;k <= n/2 + 1- i;k++){  
		            System.out.print(" ");  
		        }  
		        for(int k = 1;k <= i;k++){  
		            System.out.print("+ ");  
		        }  
		            System.out.println();  
		    }else{  
		        for(int k =1;k <= (i -(n/2 + 1));k++){  
		            System.out.print(" ");  
		        }  
		        for(int k = 1;k <= (2 *(n/2 + 1) - i);k++){  
		            System.out.print("+ ");  
		        }  
		        System.out.println();  
		    }     
		}
		
		System.out.println("第三个  :");
		for(int k = 1;k <= n/2 + 1;k++){  
		    for(int i = 1;i <= (n/2 + 1 - k);i++){  
		        System.out.print(" ");  
		    }  
		    System.out.print("*");  
		    for(int i = 1;i <= ( (k - 2) * 2 + 1);i++){  
		        System.out.print(" ");  
		    }  
		    if(k != 1){  
		        System.out.print("*");    
		    }  
		    System.out.println();  
		}  
		for(int k = n/2 ;k >=1;k--){  
		    for(int i = 1;i <= (n/2 + 1 - k);i++){  
		        System.out.print(" ");  
		    }  
		    System.out.print("*");  
		    for(int i = 1;i <= ( (k - 2) * 2 + 1);i++){  
		        System.out.print(" ");  
		    }  
		    if(k != 1){  
		        System.out.print("*");    
		    }  
		    System.out.println();  
		}  
	}

	public static void main(String[] args) {
		getDia(9);
	}
}

结果如下:

第一个 :
        +
      +++
    +++++
  +++++++
 ++++++++
  +++++++
    +++++
      +++
        +
第二个 :
      + 
     + + 
   + + + 
 + + + + 
+ + + + + 
 + + + + 
   + + + 
    + + 
      + 
第三个  :
    *
   * *
  *   *
 *     *
*       *
 *     *
  *   *
   * *
    *

java打印各种菱形