java中打印空心菱形

思路:金字塔->空心金字塔->空心菱形

import java.util.Scanner;
public class MultiplyFor{
	public static void main(String[] args){
	   Scanner myScanner = new Scanner(System.in);
	   System.out.println("请输入空心菱形的层数(奇数)");
	   int totalLevel = myScanner.nextInt();
	   if( totalLevel % 2 != 0){                                       
		   for( int i = 1; i <= (totalLevel + 1) / 2; i++){  //菱形分为两部分,先完成上半层
		   	  for( int k = 1; k <= (totalLevel + 1) / 2 - i; k++){     //i表示层数
		   	  	System.out.print(" ");                                 //k表示每层空格数
		   	  }
	       	  for( int j = 1; j <= 2 * i - 1; j++){                    
	               if( j == 1 || j == 2 * i - 1){
	              	 System.out.print("*");
	               }
	               else{
	              	System.out.print(" ");
	               }                                                  //控制菱形中间为空心
	       	  }	 
	          System.out.println();
		   }	   
		   for( int i = (totalLevel + 1) / 2 - 1; i >= 1; i--){        //打印菱形下半层
		   	  for( int k = 1; k <= (totalLevel + 1) / 2 - i; k++){
		   	  	System.out.print(" ");
		   	  }
	       	  for( int j = 1; j <= 2 * i - 1; j++){
	               if( j == 1 || j == 2 * i - 1){
	              	 System.out.print("*");
	               }
	               else{
	              	System.out.print(" ");
	               }
	       	  }	 
	          System.out.println();
		   }
	   }
	   else{
	   	System.out.println("输入的层数为偶数,请重新输入");
	   }
	}
}

你可能感兴趣的:(java)