下面是使用二维数组打印一个 10 行杨辉三角的Java代码:
public class YangHuiTriangle {
public static void main(String[] args) {
int numRows = 10; // 杨辉三角的行数
// 创建二维数组并初始化为0
int[][] triangle = new int[numRows][];
for (int i = 0; i < numRows; i++) {
triangle[i] = new int[i + 1];
}
// 填充杨辉三角的值
for (int i = 0; i < numRows; i++) {
triangle[i][0] = 1; // 每行的第一个元素为1
triangle[i][i] = 1; // 每行的最后一个元素为1
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]; // 其他元素为上一行两个元素之和
}
}
// 打印杨辉三角
for (int i = 0; i < numRows; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(triangle[i][j] + " ");
}
System.out.println();
}
}
}
运行上述代码,将会打印出一个包含10行的杨辉三角形状的输出结果。每一行的数字用空格分隔开来。例如,打印出的前几行杨辉三角如下所示:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1