user3383621
user3383621

Reputation: 203

Parsing floats from table into a 2D array

I have a file that contains a square table of floats. The file is an example, therefore the number of rows and columns may change in the other files for reading.

I am getting an out-of-bounds exception and can't figure out what the problem is.

 while ((line=bufferedReader.readLine())!=null){
       String[] allIds = line.split(tabSplit);
       String[] allFloats = new String[allIds.length-2];
//i do "length-2" because the first two columns in the table are not numbers and are
 supposed to be ignored.

       System.arraycopy(allIds, 2, allFloats, 0, allIds.length-2);
       int rows = rowsNumber;
       int cols = colsNumber;
//i have "rows" and "cols" values already extracted from the file and they return the
correct integers.

       double [][]twoD = new double[rows][cols];
       int rowCount = 0;
           for (int i = 0; i<rows; i++) {                    
            twoD[rowCount][i] = Double.parseDouble(allFloats[i]);
       }
   rowCount++;
}

             }

The table i have looks something like this, but with more rows and columns:

#18204     name01     2.67   2.79   2.87   2.7
#12480     name02     4.01   3.64   4.06   4.24
#21408     name03     3.4    3.55   3.34   3.58
#a2u47     name04     7.4    7.52   7.62   7.23
#38590     name05     7.63   7.29   8      7.72

When I print allFloats, it returns each row in a separate array correctly. I don't understand why I get an error when I try to create a 2D array.

Upvotes: 1

Views: 96

Answers (2)

Zyn
Zyn

Reputation: 614

Edit: Try the following:

int rowCount = 0;
int rows = rowsNumber;
int cols = colsNumber;
double[][] twoD = new double[rows][cols];

while ( ( line=bufferedReader.readLine() ) != null )
{
    String[] allIds = line.split( tabSplit );
    String[] allFloats = new String[allIds.length-2];

    System.arraycopy(allIds, 2, allFloats, 0, allIds.length-2);

    for (int i = 0; i<cols; i++)
    {                    
       twoD[rowCount][i] = Double.parseDouble(allFloats[i]);
    }

    rowCount++
}

Upvotes: 2

Basim Khajwal
Basim Khajwal

Reputation: 936

You are creating the two dimensional double array in every line. I would recommend first generating a two dimensional array holding all the float values for each line the after that iterate back over that array and then parse a double from that.

Upvotes: 0

Related Questions