how does this dynamic int[] array work?
in
Programming Questions
•
1 year ago
Hey Guys,
I've noticed that arrays used with split() (from the example given on the reference for split()) appear to be dynamic and require no explicit size initilialisation. That's pretty handy! The nums array below is an example.
I find this interesting because the reference page on arrays doesn't list this sort of array initialisation, this makes it a bit tricky to figure out the syntax for this case, so I ran into problems using it. I'm trying to create a similar dynamic array that stores the line numbers of certain entries of a text file stored in String lines[]. Each line is of the format '1) 5,10,12,5,0' with changing variables. The first number is the line number.
I've noticed that arrays used with split() (from the example given on the reference for split()) appear to be dynamic and require no explicit size initilialisation. That's pretty handy! The nums array below is an example.
- int[] nums; // array to store numbers
- String numbers = "8 67 5 309";
- nums = int(split(numbers, ' '));
I find this interesting because the reference page on arrays doesn't list this sort of array initialisation, this makes it a bit tricky to figure out the syntax for this case, so I ran into problems using it. I'm trying to create a similar dynamic array that stores the line numbers of certain entries of a text file stored in String lines[]. Each line is of the format '1) 5,10,12,5,0' with changing variables. The first number is the line number.
- int pen_down_lines[]; // array to store data
- int k = 0; // index of the array
- for (int i = 0; i<lines.length; i++){ // for each line
- String temp[] = split(lines[i], ") "); // split original string into line numbers and data
- nums = float(split(temp[1], ", ")); // parse data with comma operator
- if (nums[4]==0){ // if a 'pen down' command is located
- print(int(temp[0]) + ") "); // print the line number
- int h = int(temp[0]); // extract the line number
- pen_down_lines[k] = h; // store the line number in an array
- k++; // increment the index
- }
- }
I get a Null Pointer Exception on line 13. Why is this syntax invalid for this case but not for the case on line 7?
I realise there are other ways to use dynamic and undefined arrays in Processing (I've done it before), this just seems like an elegant solution that would be great if I could get it to work.
Thanks,
Ad
I realise there are other ways to use dynamic and undefined arrays in Processing (I've done it before), this just seems like an elegant solution that would be great if I could get it to work.
Thanks,
Ad
1