Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading data from file to Vector structure

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 ?

like image 612
sasklacz Avatar asked May 29 '10 13:05

sasklacz


1 Answers

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.

like image 184
John Smith Avatar answered Oct 17 '22 19:10

John Smith