FAQ
Cover
This is the archive Discourse for the Processing (ALPHA) software.
Please visit the new Processing forum for current information.

   Processing 1.0 _ALPHA_
   Programming Questions & Help
   Syntax
(Moderators: fry, REAS)
   Appending to an array?
« Previous topic | Next topic »

Pages: 1 
   Author  Topic: Appending to an array?  (Read 421 times)
rgovostes

rgovostes
Appending to an array?
« on: Sep 5th, 2003, 1:09am »

I have a variable which stores the current position of my "turtle". Occasionally, I'd like my script to generate another turtle, and add it to this variable (which is an array of turtle coordinates).
 
Is there some way to append to an array?
 
arielm

WWW
Re: Appending to an array?
« Reply #1 on: Sep 5th, 2003, 1:13am »

maybe this one:
http://proce55ing.net/discourse/yabb/board_Syntax_action_displa_y_num_1049409014.html
 

Ariel Malka | www.chronotext.org
rgovostes

rgovostes
Re: Appending to an array?
« Reply #2 on: Sep 5th, 2003, 2:01am »

Ah thanks. I wonder why that didn't show up when I ran my search. Here's my code, adapted from the one in that thread.  
 
Code:
void newTurtle(int newx, int newy) {
  int tempx[] = new int[x.length + 1];
  int tempy[] = new int[y.length + 1];
  System.arraycopy(x, 0, tempx, 0, x.length);
  System.arraycopy(y, 0, tempy, 0, y.length);
   
  x = tempx;     y = tempy;
  x[x.length] = newx; y[y.length] = newy;
}

 
However, when I run "newTurtle(20, 20)" it causes an ArrayIndexOutOfBoundsException. It happens even if I replace those "+ 1"s with "<< 1"s, as in the example.
 
benelek

35160983516098 WWW Email
Re: Appending to an array?
« Reply #3 on: Sep 5th, 2003, 4:17am »

that thread makes use of old syntax. though i can't check if it's working in the latest release from where i am right now, here's what should work:
 
Code:

void newTurtle(int newx, int newy) {  
  int[] tempx = new int[x.length + 1];  
  int[] tempy = new int[y.length + 1];  
  System.arraycopy(x, 0, tempx, 0, x.length);  
  System.arraycopy(y, 0, tempy, 0, y.length);  
   
  tempx[x.length] = newx;
  tempy[y.length] = newy;  
  x = tempx;
  y = tempy;  
}

 
you can't use myarray[myarray.length], because the largest index of any array is myarray[myarray.length-1]... that's what's causing the exception in your code.
 
benelek

35160983516098 WWW Email
Re: Appending to an array?
« Reply #4 on: Sep 5th, 2003, 4:20am »

sorry, i should make the comment that in the line...
 
Code:
tempx[x.length] = newx;

 
... (x.length) == (tempx.length-1)
 
rgovostes

rgovostes
yay
« Reply #5 on: Sep 5th, 2003, 1:00pm »

It works, thanks.
 
Need to iron out a few bugs in my code still, but I'll post whatever I get done.
 
Pages: 1 

« Previous topic | Next topic »