1

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

0

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I followed your suggestion but I still get the null pointer exception problem. @dasblinkenlight
@JedrekFadul A more conservative check would go like this: field1!=null && field1[row] != null && field1[row][col] != null && !( field1[row][col].harvested ). Usually, though, this indicates that the setup hasn't set the array up in a way to make all cells of 2D array available.
0

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

1 Comment

I did: @shimonb89 public Farm() { field1 = new Crops[104][104]; }
0

Reverse the order of the expressions in the if statement:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.