views:

32

answers:

2

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 ?

+3  A: 

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.

John Smith
You're so damn right ! Thanks !
owca
+1  A: 

You are basically adding the same array three times to the Vector while updating its value (that's why the value you have it's the last one in the file).

At the end you will have 3 references in the Vector that points to the same variable, you need to instantiate a new one on every iteration, not just at the beginning. This because vec is not duped when you add it to the vector, just its reference is passed.

Jack