Java - NullPointerException after array initialization and when testing an array using a class method

I am trying to initialize an array and then check its values ​​using the class method. I initialized the array and already successfully tested it inside the constructor, so it looks like the array was filled, but as soon as I try to check it in the Main method, it throws a NullPointer exception.

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

This is almost the same as the reference data exists inside the constructor, but then does not exist outside of it. When I comment out the loop forand the line boolean[] ....above it and uncomment my line grid = new boolean[] ...., everything works fine, but I want to choose the number of sides when creating an instance of the object.

EDIT - , 19 (firstGrid.testSqr(0)) 20 (firstGrid.grid[0]).

1D, 2D-. ?

:

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)
+4
4

:

boolean[] grid = new boolean[sides];

, .

:

grid = new boolean[sides];

.

, . , . , , "" .

+4
boolean[] grid = new boolean[sides];

boolean, .

grid = new boolean[sides];

.

+3

boolean[]. . ,

boolean[] grid = new boolean[sides];

grid = new boolean[sides];

. , .

+1

, grid, local grid, , .

:

 boolean[] grid = new boolean[sides]

to

 grid = new boolean[sides]

This will give you access to the member of the class you want.

+1
source

Source: https://habr.com/ru/post/1537287/


All Articles