|
Author |
Topic: Appending to an array? (Read 421 times) |
|
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?
|
|
|
|
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
|
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
|
Re: Appending to an array?
« Reply #4 on: Sep 5th, 2003, 4:20am » |
|
sorry, i should make the comment that in the line... Code: ... (x.length) == (tempx.length-1)
|
|
|
|
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.
|
|
|
|
|