萬物皆可TryCatch之楊輝三角

萬物皆可TryCatch之楊輝三角

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();
        int[][] arr = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i+1; j++) {
                try {
                    arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];
                    System.out.print(arr[i][j] + " ");
                } catch (IndexOutOfBoundsException e) {
                    //第一列賦值時會發生數組越界異常
                    arr[i][j] = 1;
                    System.out.print(arr[i][j] + " ");
                }
            }
            System.out.println();
        }
    }
}

try…catch語句太精妙了

發佈了16 篇原創文章 · 獲贊 10 · 訪問量 2473
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章