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

后端 未结 4 1184
借酒劲吻你
借酒劲吻你 2021-01-13 10:26

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 constr

相关标签:
4条回答
  • 2021-01-13 10:40
    boolean[] grid = new boolean[sides];
    

    Here you create a new boolean array grid which hides the class field.

    Just

    grid = new boolean[sides];
    

    and you will refer to grid class field.

    0 讨论(0)
  • 2021-01-13 10:41

    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.

    Simply change:

     boolean[] grid = new boolean[sides]
    

    to

     grid = new boolean[sides]
    

    This will ensure that you access the class member you want.

    0 讨论(0)
  • 2021-01-13 10:44

    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.

    0 讨论(0)
  • 2021-01-13 11:05

    In the constructor you initialize an array 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.

    0 讨论(0)
提交回复
热议问题