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;
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));
System.out.println("First square is :" + firstGrid.grid[0]);
}
}
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)