万物皆可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语句太精妙了

发布了15 篇原创文章 · 获赞 9 · 访问量 688

猜你喜欢

转载自blog.csdn.net/weixin_43544077/article/details/103534134