I'm working my way through The Java Programming Language, Fourth Edition - The Java Series. This is Exercise 7.3:
Write a program that calculates Pascal's triangle to a depth of 12, storing each row of the triangle in an array of the appropriate length and putting each of the row arrays into an array of 12 int arrays. Design your solution so that the results are printed by a method that prints the array of arrays using the lengths of each array, not a constant 12. Now change the code to use a constant other than 12 without modifying your printing method.
Is the following an adequate solution? Is my use of exception handling reasonable for this use case?
/**
* Defines Pascal's Triangle
*/
public class PascalsTriangle {
private final long[][] triangle;
/**
* Sole constructor
*
* @param depth the depth of the triangle
*/
PascalsTriangle(int depth) {
triangle = new long[depth][];
long upperLeft;
long upperRight;
for (int i = 0; i < depth; i++) {
triangle[i] = new long[i + 1];
for (int j = 0; j < i + 1; j++) {
if(i == 0) {
triangle[i][j] = 1; //seed the triangle
}
else {
try {
upperLeft = triangle[i - 1][j - 1];
} catch (ArrayIndexOutOfBoundsException e) {
upperLeft = 0; //upperLeft is 0 if not found
}
try {
upperRight = triangle[i - 1][j];
} catch (ArrayIndexOutOfBoundsException e) {
upperRight = 0; //upperRight is 0 if not found
}
triangle[i][j] = upperLeft + upperRight;
}
}
}
}
/**
* Prints the triangle to System.out
*/
public void printTriangle() {
for (long[] iTriangle : triangle) {
for (long jTriangle : iTriangle) {
System.out.printf("%d ", jTriangle);
}
System.out.println();
}
}
/**
* Main method - create and print a triangle
*/
public static void main(String[] arg) {
PascalsTriangle triangle = new PascalsTriangle(10);
triangle.printTriangle();
}
}