简体   繁体   English

Java - 初始化数组后和使用类方法测试数组时的 NullPointerException

[英]Java - NullPointerException after initializing array and when testing array with class method

I've been trying to initialize an array and then test its values with a class method.我一直在尝试初始化一个数组,然后用一个类方法测试它的值。 I have initialized the array and have already tested it successfully within the constructor, so it looks like the array was populated, but as soon as I try to test this in the Main method it's throwing a NullPointer exception.我已经初始化了数组并且已经在构造函数中成功地测试了它,所以它看起来像填充了数组,但是一旦我尝试在 Main 方法中测试它,它就会抛出一个 NullPointer 异常。

class PercolGrid {
    int sides;
    boolean[] grid;

    public PercolGrid (int inSides) {
        sides = inSides;
        //grid = new boolean[] {false,false,false,false,false,
        //false,false,false,false,false};
        boolean[] grid = new boolean[sides];
        for (int i = 0; i < sides; i++) {
            grid[i] = false;
            System.out.println("Setting " + i + " to " + grid[i]);
        }
        System.out.println("Checking outside FOR loop, first square is: " + grid[0]);
    }


    public boolean testSqr (int i) {
        System.out.println("Requested index is: " + i);
        return grid[i];
    }

    public static void main(String[] args){
        PercolGrid firstGrid = new PercolGrid(10);
        System.out.println("Grid created! Checking index ....");
        System.out.println("First square is :" + firstGrid.testSqr(0)); // NullPointerException
        System.out.println("First square is :" + firstGrid.grid[0]); // and here
    }
}

It's almost like the referenced data exists within the constructor but then doesn't exist outside of it.这几乎就像引用的数据存在于构造函数中,但不存在于构造函数之外。 When I comment out the for loop and the boolean[] .... line above it, and uncomment my grid = new boolean[] .... line, it all works ok, but I want to choose the number of sides when I instantiate the object.当我注释掉for循环和上面的boolean[] ....行,并取消注释我的grid = new boolean[] ....行时,一切正常,但我想选择边数我实例化对象。

EDIT - This same error occurs if I comment out line 19 ( firstGrid.testSqr(0) ) and instead run line 20 ( firstGrid.grid[0] ).编辑 - 如果我注释掉第 19 行( firstGrid.testSqr(0) )并运行第 20 行( firstGrid.grid[0] ),则会发生同样的错误。

This is a practice using a 1D array before I try the same thing with a 2D array.这是在我尝试使用 2D 数组之前使用 1D 数组的练习。 What am I missing?我错过了什么?

My output looks like this:我的输出如下所示:

Setting 0 to false
...
Setting 9 to false
Checking outside FOR loop, first square is: false
Grid created! Checking index ....
Requested index is: 0
java.lang.NullPointerException
    at PercolGrid.testSqr(PercolGrid.java:19)
    at PercolGrid.main(PercolGrid.java:25)

Your problem is with this line:您的问题出在这一行:

boolean[] grid = new boolean[sides];

This is initializing a local variable grid, not the field in the instance.这是初始化一个局部变量网格,而不是实例中的字段。

Change it to:将其更改为:

grid = new boolean[sides];

This initializes the field in the instance.这将初始化实例中的字段。

By putting the type in front you are declaring a new variable.通过将类型放在前面,您可以声明一个新变量。 When you declar a variable in a method its scope is limited to that method.当您在方法中声明变量时,其范围仅限于该方法。 Since your local variable is named the same as your instance variable it "hides" the instance variable.由于您的局部变量与您的实例变量命名相同,因此它“隐藏”了实例变量。

boolean[] grid = new boolean[sides];

Here you create a new boolean array grid which hides the class field.在这里,您创建了一个隐藏类字段的新boolean组网格。

Just只是

grid = new boolean[sides];

and you will refer to grid class field.您将参考网格类字段。

In the constructor you initialize an array boolean[] .在构造函数中,您初始化一个数组boolean[] The array is only visible in the constructor.该数组仅在构造函数中可见。 If you want to use the array of the class, then replace如果要使用类的数组,则替换

boolean[] grid = new boolean[sides];

with

grid = new boolean[sides];

. . Then you use the array of the class, not of the constructor.然后你使用类的数组,而不是构造函数的数组。

In the constructor, you created a local array with the same name as the class member grid which is being shadowed by the local grid array and that is the reason for the null pointer exception since the class member was never initialized.在构造函数中,您创建了一个与类成员grid同名的本地数组,该数组被本地grid数组遮蔽,这就是空指针异常的原因,因为类成员从未初始化。

Simply change:只需更改:

 boolean[] grid = new boolean[sides]

to

 grid = new boolean[sides]

This will ensure that you access the class member you want.这将确保您访问所需的类成员。

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

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