I'm trying to make a matrix using two dimensional arrays, but when I try to print it to the screen I get a null pointer exception
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();
}
I was hoping this would print something similar to the commented picture, but instead it is giving me java.lang.NullPointerException
I'm pretty new to java and couldn't find how to fix this anywhere, any help would be greatly appreciated.