Parsing a text file in a jagged array
I have the following file
3 2,3,4,5 6,7,8 9,10
and I am trying to convert it to pass it as a jagged double array. By this I mean, I am trying to store this as
double[][] myArray = {{2,3,4},{6,7},{9}}
double[] secondArray = {5,8,10}
I managed to get the values ββread from the file, but I got stuck on two things.
- How can I convert values ββto double array?
- How do I store the last elements in a new array?
I ran into an error because my array contains comma separated values, but how can I get the individual values ββto be converted to double? I'm still new to Java so I don't know all the built-in methods.
that's what i have so far
public double[] fileParser(String filename) {
File textFile = new File(filename);
String firstLine = null;
String secondLine = null;
String[] secondLineTokens = null;
FileInputStream fstream = null;
try {
fstream = new FileInputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
try {
firstLine = br.readLine(); // reads the first line
List<String> myList = new ArrayList<String>();
while((secondLine = br.readLine()) != null){
myList.add(secondLine);
//secondLineTokens = secondLine.split(",");
}
String[] linesArray = myList.toArray(new String[myList.size()]);
for(int i = 0; i<linesArray.length; i++){
System.out.println("tokens are: " + linesArray[i]);
}
double[] arrDouble = new double[linesArray.length];
for(int i=0; i<linesArray.length; i++)
{
arrDouble[i] = Double.parseDouble(linesArray[i]); #error here
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
source to share
It looks like the first line gives you the number of lines in the rest of the file. You can use it to make arrays ahead of time, for example:
int n = Integer.parseInt(br.readLine());
double a[][] = new double[n][];
double b[] = new double[n];
for (int i = 0 ; i != n ; i++) {
String[] tok = br.readLine().split(",");
a[i] = new double[tok.length-1];
for (int j = 0 ; j != a[i].length ; j++) {
a[i][j] = Double.parseDouble(tok[j]);
}
b[i] = Double.parseDouble(tok[tok.length-1]);
}
Likewise, you can use the method String.split
to find out how many entries should be added to the jagged array. This way the code becomes much shorter because you can preallocate all your arrays.
source to share