打印杨辉三角
1.写出打印方法
将杨辉三角内容填写进二维数组里面,然后打印,此时会出现一个问题:杨辉三角里面没有0,如果直接遍历数组会出现将0打印出来,不满足需求,所以在打印方法中增加一个判断,将0屏蔽掉。
package com.excersice;
public class Demo04 {
public void printTriangle(int[][] arrays) {
for (int i = 0; i < arrays.length; i++){
for (int j = 0; j<arrays[i].length; j++){
//如果是0,就输出空格
if (arrays[i][j]==0){
System.out.print("\t");;
}else {
System.out.print(arrays[i][j]+"\t");
}
}
System.out.println(); //输出空行
}
}
}
2.编写杨辉三角
需求:打印杨辉三角(行数可以从键盘输入)
1 0 0 0 0 0 0
1 1 0 0 0 0 0
1 2 1 0 0 0 0
1 3 3 1