2

I am trying to open a CSV via LoadTable with Processing 2 then parse a column as an array.

I have this so far:

Table table;
void setup() {
table = loadTable("random.csv", "header");

If I do something like this:

for (TableRow row : table.rows()) {
    int nums = row.getInt("Column1");
    println(nums);
    }

It displays all of the values in my table like it should. I would like to now store this into an array... e.g. int [ ]

Any help?

3 Answers 3

2

Just create array and store it in it :)

    int size = table.rows().size();
    int[] array = new int[size];        
    int i = 0;
    for (TableRow row : table.rows()) {
        int nums = row.getInt("Column1");
        println(nums);
        array[i] = nums;
        i++;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Where does the function size() come from? It doesn't seem to like that.
can you please explain size() function
0

It can also be done using getIntColumn() in one line: int[] num = table.getIntColumn("Column1")

So maybe it's even not necessary as you can do something like table.getIntColumn("id")[10]

here a running example:

//building a sample table
//not your case...
Table table;
TableRow[] someRows = new TableRow[40];

void setup() {

  table = new Table();

  table.addColumn("id");

  for (int i=0; i < someRows.length; i++) {
    someRows[i] = table.addRow();
    someRows[i].setInt("id", i);
  } 

  ///


  //here :) one line.
  int[] ids = table.getIntColumn("id");


  println(ids);

  // or direct approach
  println("without intermediary Array: row 10 = " + table.getIntColumn("id")[10]);
}

Comments

0

Although @Libik's answer will work, another option is to create an ArrayList

List<Integer> myNums = new ArrayList<>();
for (TableRow row : table.rows()) {
    int nums = row.getInt("Column1");
    myNums.add(nums)
    println(nums);
    }

The advantage here is the ArrayList can grow as you need it to and needn't be pre-allocated.

If you specifically need an array of ints for the final result, and not an ArrayList, the existing answers to this SO question talk about how to do the conversion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.