java二维数组小练习: 输出杨辉三角
如图:
package com.jh.array;
import java.util.Scanner;
public class TwoDimensionArray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("请输入杨辉三角的行数:");
int yang = scan.nextInt();
int[][] yangHui = new int[yang][];
for(int i = 0;i < yang;i++) {
yangHui[i] = new int[i+1];
//元素赋值
yangHui[i][0] = yangHui[i][i] = 1;
for(int j = 1;j < yangHui[i].length-1;j++) {
yangHui[i][j] = yangHui[i-1][j-1] + yangHui[i-1][j];
}
}
//遍历数组
for(int i =0;i < yangHui.length;i++) {
for(int j = 0; j < yangHui[i].length;j++) {
System.out.print(yangHui[i][j]+"\t");
}
System.out.println();
}
}
}