Disclaimer: This is homework, so I am not looking for an exact answer because I'd like to do this on my own. I have to read a matrix from a text file that is filled with doubles and put into a 2D array. I'm currently struggling to find where exactly my problem lies in my code because I know how to use the built in Java Scanner for a normal array. My code below always give me a NullPointerException error which means my matrix 2D array is empty.
public Matrix(String fileName){
//reads first double and puts it into the [1][1] category
//then moves on to the [1][2] and so on
//once it gets to the end, it switches to [2][1]
Scanner input = new Scanner(fileName);
int rows = 0;
int columns = 0;
while(input.hasNextLine()){
++rows;
Scanner colReader = new Scanner(input.nextLine());
while(colReader.hasNextDouble()){
++columns;
}
}
double[][]matrix = new double[rows][columns];
input.close();
input = new Scanner(fileName);
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
if(input.hasNextDouble()){
matrix[i][j] = input.nextDouble();
}
}
}
}
My text file:
1.25 0.5 0.5 1.25
0.5 1.25 0.5 1.5
1.25 1.5 0.25 1.25