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

后端 未结 4 1187
借酒劲吻你
借酒劲吻你 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: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.

提交回复
热议问题