It's easier to load/process CSV data in Processing using loadTable()
Notice this line in the example:
table = loadTable("data.csv", "header");
You can specify the table has a header which is pretty cool, because you could do something like:
float[] myColumn = table.getFloatColumn("myColumnName");
Another advantage is you can check the table was loaded/parsed successfully which would help verify / debug data. For example, if your table has string values which may contain comma(',') when it shouldn't as it's the separator
Speaking of separators, is you separator comma (which would be an CSV) or '.' ? :
String[] dataStr = split(lines[i], '.');
This is confusing because it may be also used for floating point values.
If you want to parse the data manually you can of course, but add more error checking as every step could have a problem. Here's an idea based on your code:
float[][] data;
void setup() {
String lines [] = null;
try{
lines = loadStrings("data.csv");
println(" There are " + lines.length + " lines ");
}catch(Exception e){
println("error loading data.csv");
e.printStackTrace();
exit();
}
data = new float[2][lines.length-1];
String[] header = split(lines[0], ',');
printArray(header);
for (int i = 1; i < lines.length; i++) {
String[] dataStr = split(lines[i], ',');
if(dataStr == null){
println("error parsing line",lines[i]);
continue;
}
if(data.length < 2){
println("line contains less than 2 values");
printArray(dataStr);
continue;
}
data[0][i-1] = float(dataStr[0]);
data[1][i-1] = float(dataStr[1]);
println(data[0][i-1] + " " + data[1][i-1]);
}
}
void draw () {
}
It is assuming the CSV used comma(,
) as a separator and I may be wrong: maybe the data is from a different locale where floating point numbers are separated by ,
instead of .
and .
dot is used to separate values ? Even so, you still need double check your CSV because that may still break parsing. For example:
println(float("3,14"));
prints NaN
where as
println(float("3.14"));
prints 3.14 as expected.
It might be easier to use find/replace all with a text editor on the CSV to ensure it uses ,
to separate values (between columns of a row) and .
to separate the integer from the fractional part of a floating point number.
If the CSV opens succefully and looks right in something like Excel / OpenOffice Calc / Google Sheets / etc. then it should(famous last words :)) easy to parse in Processing too.