2015-10-05 64 views
-2
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);

+0

你能帮助我们并告诉我们哪一行是52? –

+0

提示:你在哪里给'temp [0]分配了什么? –

回答

-1

matrix[0]为空(从未初始化),并在显示方法,取消引用它length

+0

谢谢。我按照你说的和显示器的工作。 – wyattrwb

相关问题