(Java)为什么此构造函数会导致空指针异常?

时间:2019-10-19 06:32:30

标签: java constructor

我正在尝试使用二维数组制作矩阵,但是当我尝试将其打印到屏幕上时,出现空指针异常

import java.util.concurrent.ThreadLocalRandom; 
public class GridWorld {
  // data

  int [][] grid; // a "r by c" grid will all entries of type int
  int r; // no. of rows 
  int c; // no. of cols

  final static int ROW = 4;  // Default row size 
  final static int COL = 4;  // Default col size

  // constructors 
  // 1. default constructor: construct a 4x4 Grid of int
  //    the entry at row i and col j is  4*i+j+1 
  public GridWorld() {
    r=4;
    c=4;
    for(int i =0;i<r;i++){
      for(int j=0; j<c; j++){
        grid[i][j] = 4*i+j+1;}}

  }
   * -----------------------------
     |    1 |    2 |    3 |    4 |
     -----------------------------
     |    5 |    6 |    7 |    8 |
     -----------------------------
     |    9 |   10 |   11 |   12 |
     -----------------------------
     |   13 |   14 |   15 |   16 |
     -----------------------------
  */
 public void display() {
   System.out.println("-----------------------------");
   for(int i=0;i<this.r;i++){
     for(int j =0;j<this.c;j++){
       System.out.print("|    "+this.getVal(i,j)+" ");}
     System.out.println(" |");
     System.out.println("-----------------------------");}

 }
     GridWorld grid1 = new GridWorld();
     grid1.display();
}


我希望它能打印出与评论图片相似的图片,但它却给了我java.lang.NullPointerException

我对Java很陌生,无法在任何地方找到解决方法,任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

在默认构造函数中初始化网格数组时,您没有初始化网格数组是因为它引发了空指针异常

添加此语句

grid = new int [ROW] [COL];