Java:利用二维数组构建杨辉三角(帕斯卡三角)
作者:互联网
package com.zbj.demo;
import java.util.Scanner;
import org.junit.Before;
import org.junit.Test;
public class PascalTriangle {
int n = 0;
@Before
public void scan() {
Scanner scan = new Scanner(System.in);
System.out.println("请输入杨辉三角的行数:");
while (n <= 2) { // 控制正确行数
n = scan.nextInt();
if (n <= 2) {
System.out.println("杨辉三角必须大于2行,请重新输入");
}
}
}
@Test
public void pascaltriangle() {
int[][] arr = new int[n][n];
// 每行的首尾都为1
for (int i = 0; i < arr.length; i++) {
arr[i][0] = 1;
arr[i][i] = 1;
}
// 每行的第二列起都是上一行的同一列+上一行的前一列
for (int i = 2; i < arr.length; i++) {
for (int j = 1; j < i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
}
for (int i = 0; i < arr.length; i++) { // 遍历杨辉三角
for (int j = 0; j <= i; j++) { // 后面无用部分无需遍历
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
标签:Java,Scanner,scan,System,帕斯卡,杨辉三角,import,public 来源: https://blog.csdn.net/weixin_43810579/article/details/89880917