I am reading a text file representing a maze pattern.
each line is read into a 1d char array and then the one 1d array is inserted into the 2d char array.
In the following method get a nullpointerexception at
line = (input.readLine()).toCharArray();
private void fillArrayFromFile() throws IOException
{
BufferedReader input = new BufferedReader(new FileReader("maze.txt"));
//Read the first two lines of the text file and determine the x and y length of the 2d array
mazeArray = new char[Integer.parseInt(input.readLine())][Integer.parseInt(input.readLine())];
char [] line = new char[10];
//Add each line of input to mazeArray
for (int x = 0; x < mazeArray[0].length; x++)
{
line = (input.readLine()).toCharArray();
System.out.print(x + " : ");
System.out.println(line);
mazeArray[x] = line;
}
}
The obvious answer is that
input.readLine()is returningnull, and since you are calling a method of an object that is pointing to nothing, you are getting aNullPointerException.The root of this problem though, is the discrepancy between your perception of rows and columns and that of the text file. Also, you are looping through the incorrect index, if I am reading your code correctly.
Here is an example text file:
A good way of thinking about this is to think about the number of rows and columns you have.
For example, the text file above says “I have 4 columns and 6 rows”.
That also means
xranges from0to3andyranges from0to5.In your terms, the x-length is the number of columns, and the y-length is the number of rows.
Of course, remember that rows go across, and columns go downwards, assuming the indices are increasing.
This is very important. Because x and y are essentially indices to a specific location in the grid.
Although that is probably the cause, you also have a few semantic errors that I’ll fix below.