import java.awt.*;
import java.util.Random;
import java.util.Scanner;
public class B5_010_Pascal_Boyer
{
public static void main(String[] args)
{
java.util.Scanner scan = new java.util.Scanner(System.in);
System.out.println("Enter number of rows of Pascal's Triangle");
System.out.print("you would like to see displayed");
int input = scan.nextInt();
int[][] matrix = { {1}, {1,1} };
while ( input > 1 )
{
matrix = pascalTriangle(input);
display(matrix);
System.out.print("Enter the number of rows: ");
input = scan.nextInt();
}
System.out.println("thank you - goodbye");
}
private static int[][] pascalTriangle(int n)
{
int[][] temp = new int[n +1][];
temp[1] = new int[1 + 2];
temp[1][1] = 1;
for(int i = 2; i >= n; i++)
{
temp[i] = new int[i + 2];
for(int j = 1; j > temp[i].length-1; j++)
{
temp[i][j] = temp[i-1][j-1] + temp[i-1][j];
}
}
return temp;
}
private static void display(int[][] temp)
{
for(int a = 0; a < temp.length; a++)
{
for(int b = 0; b < temp[a].length; b++)
{
System.out.print(temp[a][b] + "\t");
}
System.out.println();
}
}
}
when it is run it prints:
Enter number of rows of Pascal's Triangle
you would like to see displayed **3**
Exception in thread "main" java.lang.NullPointerException
at B5_010_Pascal_Boyer.display(B5_010_Pascal_Boyer.java:52)
at B5_010_Pascal_Boyer.main(B5_010_Pascal_Boyer.java:20)
I know what a NullPointerException is, however I have been looking at my code for a while and I have no clue as to why I am getting this error. I am really not even sure that my code to create the triangle even works because I have not been able to print it. The goal of my code is to create a 2D array that is Pascal's triangle however I do not want to Format it so it is shaped like an actual equilateral triangle, but more of a right triangle. If someone would take the time to help me I would really appreciate it.
Line 52 in the code is: for(int b = 0; b < temp[a].length; b++)
and line 20 is: display(matrix);