Background: I am writing a program that uses BufferedReader to store several lines of a text file into a String array.
Example of text file:
4 5
4 5 2 3 3
3 2 1 3 2
2 3 1 2 3
3 3 2 1 2
2 3 1 2 1
ArrayList of textfile lines:
["4 5"]["4 5 2 3 3"]["3 2 1 3 2"]["2 3 1 2 3"]["3 3 2 1 2"]["2 3 1 2 1"]
Need a 2D array like this:
[3][2]1[3][2]
[2][3]1[2][3]
[3][3]2[2]
The first line(array element) essentially indicates the size of my array which I successfully created a new array using array.split(" "): [4][5]. The second line is used for a different method which was successful as well using array.split(" "). I'm having an issue with lines 3-6.
void allocatedUnits(){
String au;
start_alloRow = 2; //start row 2 of text file
end_alloRow = start_alloRow + num_process; //length is how many processes were indicated
for (int i = start_alloRow; i < end_alloRow; i++){
au = fileArray[i]; //fileArray element i into String au (i=start-end)
String[] array = au.split(" "); //split String au "i" into array elements
for (int j = 0; j <= array.length; j++){ //for element j 0-arraylength (0-num_resource)
allocatedArray[i][j] = Integer.parseInt(array[j]); //use alloArray[i] row for [j] element
System.out.println(allocatedArray[i][j]); //print each element
}
}}
The error I get is NullPointerExcetion at the line of allocatedArray[i][j] = Integer.parseInt(array[j]);
I have printed the String[] array elements without the 2D array and it prints correctly, so I'm unsure if I'm creating the 2D array incorrectly.
EDIT:// I now have an ArrayIndexOutOfBounds exception which I understand, but don't know how to fix it. This is my updated code with initialized array (which helped)
void allocatedUnits(){
String au;
start_alloRow = 2; //start row 2 of text file
end_alloRow = start_alloRow + num_process; //length is how many processes were indicated
allocatedArray = new int[num_process][num_resource];
for (int i = start_alloRow; i < end_alloRow; i++){
int k = 0;
au = fileArray[i]; //fileArray element i into String au (i=start-end)
String[] array = au.split(" "); //split String au "i" into array elements
for (int j = 0; j < array.length; j++){ //for element j 0-arraylength (0-num_resource)
allocatedArray[k][j] = Integer.parseInt(array[j]); //use alloArray[i] row for [j] element
System.out.println(allocatedArray[k][j]); //print each element
k++;
}
}
}