阅读量:0
下面是一个用Java输出杨辉三角的示例代码:
import java.util.*; public class YangHuiTriangle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入要输出的行数:"); int numRows = sc.nextInt(); List<List<Integer>> triangle = generate(numRows); for (List<Integer> row : triangle) { for (int num : row) { System.out.print(num + " "); } System.out.println(); } } public static List<List<Integer>> generate(int numRows) { List<List<Integer>> triangle = new ArrayList<>(); if (numRows == 0) { return triangle; } List<Integer> firstRow = new ArrayList<>(); firstRow.add(1); triangle.add(firstRow); for (int i = 1; i < numRows; i++) { List<Integer> prevRow = triangle.get(i - 1); List<Integer> currRow = new ArrayList<>(); currRow.add(1); for (int j = 1; j < i; j++) { currRow.add(prevRow.get(j - 1) + prevRow.get(j)); } currRow.add(1); triangle.add(currRow); } return triangle; } }
运行这段代码后,输入要输出的行数,程序将会输出相应行数的杨辉三角。