java - (Java) 为什么这个构造函数会导致空指针异常?

标签 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 很陌生,找不到如何解决这个问题,任何帮助将不胜感激。

最佳答案

在默认构造函数内初始化网格数组,您没有初始化网格数组,这是它抛出空指针异常的原因

添加此语句

grid =new int[ROW] [COL] ;

关于java - (Java) 为什么这个构造函数会导致空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58461129/

相关文章:

java - Apache Pig在AWS EMR Hadoop集群中无输出

c++ - 段错误而不是构造函数调用

python - 如何在没有元类的情况下将不同的参数传递给 __new__ 与 __init__

javascript - 类/原型(prototype)继承后获取当前 'class name'

python - 部分构造函数初始化的性能

c++ - 有没有一种方法可以根据创建的派生类分配成员?

Java 1.8 边框渲染不正确

java - 编译 Dropwizard 代码,无需迁移.xml

javax.net.ssl.SSLHandshakeException : java. security.cert.CertificateException:没有可用的 X509TrustManager 实现

java - Android 中的 Button 关键字错误