java.lang.NullPointException.

ilaf
ilaf used Ask the Experts™
on
I have a run time error (with the array of object). I recieved the message java.lang.NullPointException.

This is my program:-

import java.io.*;
import java.lang.*;
import java.util.Random;

 class reg{
     
        int Rr;
        int Rs;
 }  

class sort3{
 
public static void main(String args[])throws IOException
{
       reg Matrix[][]= new reg[64][64];
    int n,i,j;
       BufferedReader in = new BufferedReader( new  
                          InputStreamReader(System.in));
               
       System.out.print(" enter n : ");
    n = Integer.parseInt(in.readLine());    
   
       Random rand = new Random();
       for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        {                
               System.out.println(j);                
         Matrix[i][j].Rs =0;  // ERROR POSITION
               System.out.println(Matrix[i][j].Rs);
    Matrix[i][j].Rr = (64*rand.nextInt());// ERROR  
                                                   
               
        }
   
   
   
}
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
No memory is allocated for the array in reg
Top Expert 2016

Commented:
For a square matrix:


class Reg {
  int[][] matrix;

  public Reg(int sz) {
    matrix = new int[sz][sz];
  }
}

Commented:
You need this line,
Matrix[i][j] = new reg(); before the line where you are getting the error,
**********************************************************
ie.

       for(j=0;j<n;j++)
       {                
          System.out.println(j);                
          Matrix[i][j] = new reg(); //ADD HERE
          Matrix[i][j].Rs =0;  // ERROR POSITION
          System.out.println(Matrix[i][j].Rs);
          Matrix[i][j].Rr = (64*rand.nextInt());// ERROR  
       }
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

u should allocate all reg objects in the matrix:

...
reg Matrix[][] = new reg[64][64];
   for (int i=0; i<64; i++)
      for (int j=0; j<64; j++)
        Matrix[i][j] = new reg();
...

-gkern
-gkern is right, all objects should be initialized because they default to null.

-Better yet, make the array after the user inputs the n variable. (make sure its not too big)
Top Expert 2016

Commented:
>>gkern is right, all objects should be initialized because they default to null.

Yes, but i'd already said that:

>>No memory is allocated for the array in reg

?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial