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();
}
}
}
运行时打印:
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)
我知道NullPointerException是什么,但是我一直在查看我的代码,我不知道为什么我会收到此错误。我甚至不确定我创建三角形的代码是否有效,因为我无法打印它。我的代码的目标是创建一个Pascal三角形的2D数组,但我不想格式化它,使其形状像实际的等边三角形,而更像是一个直角三角形。如果有人愿意花时间帮助我,我会非常感激。
代码中的第52行是:for(int b = 0; b < temp[a].length; b++)
第20行是:display(matrix);
答案 0 :(得分:-1)
matrix[0]
为空(从未初始化),在显示方法中,您取消引用length