I have a small assignment where I have to use a 2d array to produce Pascal's triangle. Here is my code, and it works. There is an extra credit opportunity if I display the triangle like so:
However, my spacing is not formatted like that. it simply displays the numbers all lined up on the left. its hard to describe but if you run it you will see what I mean.
Here is my code:
public class Pascal {
public static final int ROW = 16;
public static void main(String[] args) {
int[][] pascal = new int[ROW + 1][];
pascal[1] = new int[1 + 2];
pascal[1][1] = 1;
for (int i = 2; i <= ROW; i++) {
pascal[i] = new int[i + 2];
for (int j = 1; j < pascal[i].length - 1; j++) {
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
}
for (int i = 1; i <= ROW; i++) {
for (int j = 1; j < pascal[i].length - 1; j++) {
System.out.print(pascal[i][j] + " ");
}
System.out.println();
}
}
}
If someone could help me figure out how to add the correct spacing to my program to produce the output desired in the picture, that would be great. I know I need to put a System.out.print(" ")
somewhere. I just dont know where.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…