我正在尝试使用二维数组创建一个矩阵,但是当我尝试将其打印到屏幕上时,出现空指针异常
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/