0

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.

new2java
  • 39
  • 5
  • When you have a problem like this, first search - this one has been asked a hundred times before. If you didn't find anything useful in what you turned up say so- tell us what you've tried. If you didn't find anything, tell us what you searched for. If you think your problem is new make sure you tell us which line the error is occurring on so we don't have to read your whole program and work it out ourselves. Finally, post a complete set of code to reproduce the issue; you don't seem to have posted the getValue method which seem to me the most likely candidate for the source of the error – Caius Jard Oct 19 '19 at 06:38

1 Answers1

0

Inside the default constructor initialize the grid array you did not initalize the grid array that the reason it throws null pointer exception

Add this statement

grid =new int[ROW] [COL] ;

S Manikandan
  • 148
  • 8