Java实现任意行数的杨辉三角

输入所需行数,Java实现杨辉三角的输出

class yanghui{
    //行数及储存的杨辉三角
    private int row;
    private int data[][];

    public yanghui()
    {
        this.setRow();
    }
    public void setRow(){
        Scanner in=new Scanner(System.in);
        System.out.println("请输入行数:");
        this.row=in.nextInt();
    }
    public void seta(int b[][]){
        this.data=b;
    }
    public void setA(){
        int a[][]=new int[this.row][this.row];
        for(int i=0;i<this.row;i++){
            for(int j=0;j<=i;j++){
                if((j==0)||(j==(this.row-1))){
                    a[i][j]=1;
                }else{
                    a[i][j]=a[i-1][j-1]+a[i-1][j];
                }
            }
        }
        this.seta(a);
    }
    public void print(){
        if(this.row>0){
            this.setA();
            System.out.println("杨辉三角如下:");
            for(int i=0;i<this.row;i++){
                for(int j=0;j<=i;j++){
                    System.out.print(this.data[i][j]+"\t");
                }
                System.out.println();
            }
        }else{
            System.out.println("不存在!");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Hello_Peter_Chan/article/details/79361437
今日推荐