下面是一個用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;
}
}
運行這段代碼后,輸入要輸出的行數,程序將會輸出相應行數的楊輝三角。