I'm trying to parse through fixed-width formatted file extracting x,y values of points from it, and then storing them in int[]
array inside a Vector.
Text file looks as follows :
0006 0015
0125 0047
0250 0131
That's the code :
Vector<int[]> vc = new Vector<int[]>();
try {
BufferedReader file = new BufferedReader(new FileReader("myfile.txt"));
String s;
int[] vec = new int[2];
while ((s = file.readLine()) != null) {
vec[0] = Integer.parseInt(s.substring(0, 4).trim());
vec[1] = Integer.parseInt(s.substring(5, 8).trim());
vc.add(vec);
}
file.close();
} catch (IOException e) {
}
for(int i=0; i<vc.size(); i++){
for(int j=0; j<2; j++){
System.out.println(vc.elementAt(i)[j]);
}
}
But the output shows only last line.
250
131
250
131
250
131
Should I somehow use Vector.nextElement()
here to get all my data ?
You need to create a new int[] on each pass of the loop
while ((s = file.readLine()) != null) {
int[] vec = new int[2];
vec[0] = Integer.parseInt(s.substring(0, 4).trim());
vec[1] = Integer.parseInt(s.substring(5, 8).trim());
vc.add(vec);
}
Otherwise you just have multiple references to the same array, which you overwrite on each pass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With