Hello guys, I’m trying to write an object with arrays in it. but i want to make the length of the array as a variable so i can manipulate in the parameters.
so i set the array length as n in this code.
Snake snake1;
void setup(){
//size
size(400,300);
//object
snake1 = new Snake(50,200,50,10,20);
}
void draw(){
snake1.rule();
//snake1.circle();
}
class Snake {
int n;
float r, g, b, s;
//arrays
int[] xpos = new int [n];
int[] ypos = new int [n];
Snake(int n_, float r_, float g_, float b_, float s_) {
n=n_;
r=r_;
g=g_;
b=b_;
s=s_;
//initialize
for (int i=0; i<xpos.length; i++) {
xpos[i] = 0;
ypos[i] = 0;
}
}
void rule() {
//latest i = mouse position
xpos[xpos.length-1] = mouseX;
ypos[ypos.length-1] = mouseY;
//former position
for (int i=0; i< xpos.length-1; i++) {
xpos[i]= xpos[i+1];
ypos[i]= ypos[i+1];
}
for (int i=0; i<xpos.length; i++) {
noStroke();
fill(r, g, b);
circle(xpos[i], ypos[i], s);
}
}
}
But when I run it, processing informs me that ArrayIndexOutOfBoundsException: -1, pointing to line 30 :xpos[xpos.length-1] = mouseX; as an error. I thought there was sth wrong with it but after i checked many times I did’t know what went wrong. Then i thought about maybe it’s the variable n that i set in the array. so i change n into a hard-coded number 50. codes like this.
Snake snake1;
void setup(){
//size
size(400,300);
//object
snake1 = new Snake(200,50,10,20);
}
void draw(){
background(255);
snake1.rule();
//snake1.circle();
}
class Snake {
float r, g, b, s;
//arrays
int[] xpos = new int [50];
int[] ypos = new int [50];
Snake( float r_, float g_, float b_, float s_) {
r=r_;
g=g_;
b=b_;
s=s_;
//initialize
for (int i=0; i<xpos.length; i++) {
xpos[i] = 0;
ypos[i] = 0;
}
}
void rule() {
//latest i = mouse position
xpos[xpos.length-1] = mouseX;
ypos[ypos.length-1] = mouseY;
//former position
for (int i=0; i< xpos.length-1; i++) {
xpos[i]= xpos[i+1];
ypos[i]= ypos[i+1];
}
for (int i=0; i<xpos.length; i++) {
noStroke();
fill(r, g, b);
circle(xpos[i], ypos[i], s);
}
}
}
And then it works perfectly. so if i want to set the array length as a variable in the object, how can I do it? Thank you.