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();
}
}
}
當它時,它會打印:Java:爲什麼我的顯示方法給我一個NullPointerException?
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三角形的二維數組,但我不想格式化它,因此它的形狀像一個實際的等邊三角形,但更多的是一個直角三角形。如果有人會花時間幫助我,我會非常感激。
52行的代碼是:for(int b = 0; b < temp[a].length; b++)
和第20行是:display(matrix);
你能幫助我們並告訴我們哪一行是52? –
提示:你在哪裏給'temp [0]分配了什麼? –