加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Java 打印金字塔形数字图案

(2012-07-08 20:36:09)
标签:

杂谈

分类: Java
用for嵌套循环打印一个如下图案:
                                        
                                       
                                      
                                     
                          16           
                     16   32    16          
                16   32   64    32   16          
           16   32   64  128    64   32   16          
实现如下:
(若有大神路过,还请多多指教)
public class PrintPyramid {

    public static void main(String[] args) {
        int row = 7;
        for(int i = 0;i <= row;i++){
           
            //實現每行縮進
            for(int k = 0;k < (row - i);k++){
                System.out.print("     ");
            }
           
            //左半部份
            for(int j = 0;j <=i;j++){   
                //一位數的話4個空格
                if(((int)Math.pow(2, j)) < 10){
                    System.out.print("   ");
                }
                //三位數2個空格
                else if(((int)Math.pow(2, j)) > 99){
                    System.out.print(" ");
                }
                //兩位數3個空格
                else{
                    System.out.print("  ");
                }
                System.out.print(" " + (int)Math.pow(2,j));               
            }
           
            //左右縮進
            System.out.print("   ");
           
            //右半部份
            for(int l = i - 1 ;l >= 0;l--){               
                System.out.print(" " + (int)Math.pow(2, l));
                //一位數的話4個空格
                if(((int)Math.pow(2, l)) < 10){                   
                    System.out.print("   ");
                }
                //三位數2個空格
                else if(((int)Math.pow(2, l)) > 99){
                    System.out.print(" ");
                }
                //兩位數3個空格
                else{
                    System.out.print("  ");
                             
                     
            System.out.println();
        }
    }
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有