rst-2cv
rst-2cv

Reputation: 1180

How do I store int values from CSV file in separate two-dimensional array elements

If I have a CSV file with 4 numbers on one line separated by a comma, how do I ignore the first two values using openCSV?

Now, consider the following two-dimensional array:

int[][] data = new int [10][10];

and the following line from a CSV file:

54, 68, 5, 1

assuming the former is possible (ignoring the first two values on a line in a CSV file), how do I then parse the value '5' into data[0][0] and parse the value '1' into data[0][1]?

i.e.:

data[0][0] = 5;
data[0][1] = 1;

Of course, if you cannot ignore the first two values, how do I parse each value (54, 68, 5, and 1) all in separate array elements?

i.e.:

data[0][0] = 54;
data[0][1] = 68;
data[0][2] = 5;
data[0][3] = 1;

I can't find anything in the openCSV documentation that would explain how to do this, nor can I wrap my head around even doing it if there weren't a CSV file to read beforehand.

Upvotes: 1

Views: 99

Answers (1)

Robert
Robert

Reputation: 8571

Just googling "opencsv" got me to its project page. That page has the following example:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    // nextLine[] is an array of values from the line
   System.out.println(nextLine[0] + nextLine[1] + "etc...");
}

What prevents you from doing the same and just accessing the fields you want by index?

data[0][0] = nextLine[2];
data[0][1] = nextLine[3];

Upvotes: 1

Related Questions