We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Split() does not advance
Page Index Toggle Pages: 1
Split() does not advance (Read 1030 times)
Split() does not advance
Apr 22nd, 2010, 3:24am
 
I'm loading a CSV-file containing some x & y coordinates, which looks like this:

Code:
X Coordinate,Y Coordinate
992890,157287
1004879,167415
1024193,225136
1035310,241442
990688,160138
1034264,244077
1043763,212028
1000513,171618


Ofcourse, I'd like to split the values and store them in an array. I do so by doing this:

Code:
void setup() {
size(800,800);
drawVisualization("data.csv");
};

void drawVisualization(String path) {
String[] raw = loadStrings(path);

// loop through the dataset
// skip the first descriptive line
for(int line = 1; line < raw.length; line++) {
String[] trees = split(raw[line], ","); //split the raw data and store in the array
println(trees[line]); //print the array
};
}


however, if I look in my output all I see is

Code:
157287


Which means that the Split() function seems to break after the first line. The CSV-file does not seem to contain any bogus characters at the end of each line. The CSV has a length of 2250 lines, but shortening it to 200 lines does not make any difference..

Any idea what's causing this behavior?
Re: Split() does not advance
Reply #1 - Apr 22nd, 2010, 4:21am
 
Shocked I must have been out of it when I wrote this post.
See a much better answer in the next post.
Re: Split() does not advance
Reply #2 - Apr 22nd, 2010, 4:25am
 
1: You're creating a new trees[] every single line, and it ceases to exist at the end of every loop through the for(...)

2: split("123,456",",") gives ["123,"456"], i.e. a 2 element array, so you'll never have an item 3 or 4 or 5 etc in it when lines increases.

3: arrays start from 0, not 1.

What you want to do is something like:

Code:
String[][] trees=new String[lines][]; // 2 entries per line.
for(int line=0; line<raw.length; line++)
{
trees[line]=split(raw[line],",");
}

for(int i=0;i<trees.length;i++)
{
println("["+i+"] a:"+trees[i][0]+", b:"+trees[i][1]);
}
Re: Split() does not advance
Reply #3 - May 5th, 2010, 12:27am
 
Thanks! I didn't know arrays advance like that in loops. Your code helped a lot Smiley
Page Index Toggle Pages: 1