java实现杨辉三角算法

public class Test {
	private static int[][] allNum;
	private static int[] eachLayerNum;
	
	public static void main(String[] args) {
    	//层数
        int layerNum = 0;
        Scanner sc = new Scanner(System.in);
       	System.out.println("请输入打印行数:");
        layerNum = sc.nextInt();
        //执行计算
        handle(layerNum);
        //输出
        output();
	}
        
    public static void handle(int layerNum){
    	allNum = new int[layerNum][];
        for (int i = 0; i < layerNum; i++){
        	eachLayerNum = new int[i+1];
            if (i > 0){
            	for (int j = 0; j<=i; j++){
                	if (j == 0){
                    	eachLayerNum[j] = allNum[i-1][j];
                    }else if (j == i){
                    	eachLayerNum[j] = allNum[i-1][j-1];
                    }else{
                   		eachLayerNum[j] = allNum[i-1][j-1] + allNum[i-1][j];
                    }
                }
			}else{
            	eachLayerNum[i] = 1;
            }
           	allNum[i] = eachLayerNum;
        }
    }

	public static void output(){
		for (int i = 0; i < allNum.length; i++){
        	for (int j = i; j < allNum.length-1; j++){
            	System.out.print("   ");
          	}
            for (int j = 0; j < allNum[i].length; j++){
            	if (allNum[i][j] < 10){
                	System.out.print("    ");
                }else if(allNum[i][j] >= 10 && allNum[i][j] < 100) {
                	System.out.print("   ");
                }else if(allNum[i][j] >= 100&&allNum[i][j] < 1000){
                	System.out.print("  ");
                }else{
                	System.out.print(" ");
                }
               	System.out.print(allNum[i][j]);
                System.out.print(" ");
            }
            System.out.println();
        }
	}
}

在这里插入图片描述
在这里插入图片描述

发布了1 篇原创文章 · 获赞 0 · 访问量 672
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览