0
public class Bucket

{

    int rows,cols,blocked,open,full;

    public void initialize()
    {
        rows=0;
        cols=0;
        blocked=0;
        System.out.println("You were here");
    }
    public void open()
    {
        blocked=1;
    }
}

I am getting a null pointer exception when I am running the percolation class, I don't have any clue, how to get rid of it, any help will be very thankful.

public class Percolation
{

    //public Percolation(int N)
    public static void main(String args[])throws Exception
    {
        try
        {
            int N=5;
            Bucket[][] barray=new Bucket[N][N];
            for(int i=0;i<N;i++)
            {
                for(int j=0;j<N;j++)
                {
                    barray[i][j].initialize();
                    //barray[i][j].cols=0;  
                    //barray[i][j].blocked=0;           
                }
            }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }

}

Afsun Khammadli
  • 1,973
  • 3
  • 15
  • 26
Ashish Ranjan
  • 11,263
  • 4
  • 22
  • 45

2 Answers2

2

Creating an array with the new operator just allocates an array full of nulls. You still need to initialize every element separately before trying to use it:

int N=5;
Bucket[][] barray=new Bucket[N][N];
for(int i=0;i<N;i++)
{
    for(int j=0;j<N;j++)
    {
        barray[i][j] = new Bucket(); // was missing 
        barray[i][j].initialize();
    }
}

Note, however, that explicitly calling an initialize method seems weird. It would be more "java-ish" to move this logic to Bucket's constructor, or at least have the constructor call initialize itself if you really need this as a method:

public class Bucket 
{
    int rows,cols,blocked,open,full;

    public Bucket() {
        initialize();
    }

    public void initialize()
    {
        rows=0;
        cols=0;
        blocked=0;
        System.out.println("You were here");
    }

    public void open()
    {
        blocked=1;
    }

}

And then, when you initialize your array:

int N=5;
Bucket[][] barray=new Bucket[N][N];
for(int i=0;i<N;i++)
{
    for(int j=0;j<N;j++)
    {
        barray[i][j] = new Bucket(); // no need to call initialize()
    }
}
Mureinik
  • 252,575
  • 45
  • 248
  • 283
2

You create an array of Bucket objects. However, they are not initialized.

You need to create an instance of Bucket this way:

public static void main(String args[])throws Exception
{
    try
    {
        int N=5;
        Bucket[][] barray=new Bucket[N][N];
        for(int i=0;i<N;i++)
        {
            for(int j=0;j<N;j++)
            {
                barray[i][j] = new Bucket(); // Creating an instance
                barray[i][j].initialize();
                //barray[i][j].cols=0;  
                //barray[i][j].blocked=0;           
            }
        }
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}
Yeldar Kurmangaliyev
  • 30,498
  • 11
  • 53
  • 87