繁体   English   中英

空指针异常错误调用方法

[英]null pointer exception error calling method

如果我调用一个方法,我会得到这个空指针异常错误。 如果(farm1.cropStat(行,列))

这是方法

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

这是初始化

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);
    }  
 }

请帮助:(

每当你看到这样的图案

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

用等价物替换它

return someCondition.

这是同样的事情。

就错误而言,您需要颠倒检查的顺序,以便在引用该项目之前查看该项目不为null

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

运算符&&的设计方式是,一旦它看到结果将是错误的,它就会停止进一步的评估。 在上面的例子中, &&将在field1[row][col]null时停止,防止空指针异常。

您没有在任何地方初始化field1 ,因此当您尝试为其赋值时它为 null。

颠倒 if 语句中表达式的顺序:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM