首页 > 编程语言 >用java实现按层数打印空心菱形

用java实现按层数打印空心菱形

时间:2022-09-18 14:23:06浏览次数:79  
标签:java 打印 System 空心 菱形 层数 out

 

//////////////打印空心菱形的代码
class Homework15{
    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        System.out.println("请输入菱形的层数必须为奇数:");
        int totalLevel = myScanner.nextInt();
        for ( int i = 1; i<= totalLevel; i++) {
            // 打印 菱形的上半部
            if( i <= ( totalLevel/2+1) ){
                //打印空格
                for ( int k = 1; k <= (( totalLevel/2+1)-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(" ");    
                }
            }    
            else {                        
                // 再打印 菱形的下半部 == 打印倒立空心金字塔
                // 定义下半部金字塔层数
                int downI = (totalLevel-i+1);
                //打印空格
                for ( int k = 1; k <= (i-(totalLevel/2+1)); k++)
                        System.out.print(" ");
                //打印 *        
                for ( int j = (2*downI-1); j >= 1; j--) { //j=7
                    if( j == 1 || j == (2*downI-1))
                        System.out.print("*");
                    else System.out.print(" ");    
                }
            }    
            System.out.println();
        }

    }
}

 

标签:java,打印,System,空心,菱形,层数,out
From: https://www.cnblogs.com/yinzhenzhike/p/16704742.html

相关文章