Skip to content
Advertisement

null pointer exception error calling method

I get this null pointer exception error if i call a method. if (farm1.cropStat(row, col) )

here’s the method

public boolean cropStat(int row, int col)
{
    if( !( field1[row][col].harvested ) && field1[row][col] != null  )       
    {
        return true;
    }
    else
    {
        return false;
    }
}

here’s the initialization

public void initializeCrops()
{
    Random rnd = new Random();
    int rRow=-1, cCol=-1;
    int i, j;

    for (i = 0; i< 74; i++)
    {   
        while(rRow <0 || cCol <0)
        {
            rRow = rnd.nextInt() % 104;
            cCol = rnd.nextInt() % 104;
        }
        field1[rRow][cCol] = new Crops(rRow, cCol);
    }  
 }

pls help 🙁

Advertisement

Answer

Whenever you see a pattern that looks like this

if (someCondition) {
    return true;
} else {
    return false;
}

replace it with the equivalent

return someCondition.

It is the same thing.

As far as the error goes, you need to reverse the order of your checks in order to see that the item is not null before referencing it:

return field1[row][col] != null && !( field1[row][col].harvested );

Operator && is designed in such a way that once it sees that the result is going to be false, it stops further evaluation. In the example above, && will stop if field1[row][col] is null, preventing null pointer exception.

10 People found this is helpful
Advertisement