I am trying to read matrix data from a file and I'm not able to figure out what is wrong. This is the code that is not working:
protected static double[][] getArrayFromFile(int new_rows, int new_cols,
String file)
{
double[][] A = new double[new_rows][new_cols];
try {
Scanner fileReader = new Scanner(new File(file));
for (int i = 0; i < new_rows; i++)
for (int j = 0; j < new_cols; j++)
{
if(fileReader.hasNextDouble())
A[i][j] = fileReader.nextDouble();
else
{
System.out.println("missing numbers in file");
break;
}
}
fileReader.close();
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return A;
}
This method receives a file and the number of columns and rows to be read. It is not robust
at all but it should work if you inform the parameters correctly.
After testing it and printing the matrix, I get only zeros. I am already passing the
absolute path to the data file and I'm pretty sure that the program is finding it due to
the fact that when I pass a path that doesn't exist it shows an error message. When running debug I see that fileReader.hasNextDouble()
is always returning false, so no number is getting read. Why is this happening? I have
another method to read file from String that looks just like this and works perfectly.
Here it is:
protected double[][] getArrayFromString(int new_rows, int new_cols,
String numbers)
{
Scanner stringReader = new Scanner(numbers);
stringReader.useDelimiter("[^\\p{Alnum},\\.-]");
double[][] A = new double[new_rows][new_cols];
for (int i = 0; i < new_rows; i++)
for (int j = 0; j < new_cols; j++)
{
if(stringReader.hasNextDouble())
A[i][j] = stringReader.nextDouble();
else
{
stringReader.close();
throw new RuntimeException("\n"+""
+ "missing numbers on string");
}
}
stringReader.close();
return A;
}
I've been programming for quite a while with C and C++ and I've just started working with JAVA, so maybe there is something stupid that I'm doing. Can anyone see the mistake I'm making?
EDIT
This is the file I'm trying to read:
23.0 0.84825
188.5 6.87425
269.0 10.9595
321.0 13.08725