user4620058
user4620058

Reputation:

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 :(

Upvotes: 1

Views: 85

Answers (3)

Ren&#233; Winkler
Ren&#233; Winkler

Reputation: 7088

Reverse the order of the expressions in the if statement:

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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.

Upvotes: 1

shimonb89
shimonb89

Reputation: 318

You did not initialize field1 anywhere, so it is null when you try to assign values into it.

Upvotes: 0

Related Questions