ArrayOutOfBoundsException: x
in
Programming Questions
•
8 months ago
I keep getting this error on my array however i don't think it is out of bounds because i have specified its length. the error will give me a number but for my program they aren't out of bounds.
final int DASH_LENGTH = 10;
final int LANE_HEIGHT = 30;
final int GAP = 3;
final int DIFFICULTY = (int)random(1,6); //keep between 1 and 5
final int N_CARS = 6 + DIFFICULTY;
final int CAR_HEIGHT = 24;
final int FROG_SIZE = 24;
int score = 0;
Car[] cars;
Frog frog;
void setup() {
size(600,480);
background(255);
frog = new Frog();
cars = new Car[6 + DIFFICULTY];
for (int i=0; i<cars.length; i++) {
int carLength = (int)random(40,101);
cars[i] = new Car(carLength, CAR_HEIGHT, 15 + i*30);
}
}
void draw() {
background(255);
lanes();
for(int i = 0; i <= cars.length; i++) {
cars[i].displayTheCarMove(); /*THIS IS WHERE I GET THE ERROR. BUT ABOVE THERE IS A SIMILAR LINE OF CODE AND THAT WORKED FINE. */
}
frog.display();
}
void keyPressed() {
frog.move();
}
class Car {
float cWidth, cHeight;
float centerX, centerY;
float speed;
int shade;
Car(float cL, float cH, float lane) {
cWidth = cL;
cHeight = cH;
centerX = random(cL/2, width - cL/2);
centerY = constrain(centerY, 3 + cH/2, (6 + DIFFICULTY)*LANE_HEIGHT);
}
void displayTheCarMove() {
display();
carMove();
}
void carMove() {
centerX += speed;
if((centerX <= cWidth/2) || (centerX >= width - cWidth / 2)) {
speed *= -1;
}
}
void display() {
rectMode(CENTER);
noStroke();
fill((int)random(201));
rect(centerX, centerY, cWidth, cHeight);
}
}
Thank you in advance.
final int DASH_LENGTH = 10;
final int LANE_HEIGHT = 30;
final int GAP = 3;
final int DIFFICULTY = (int)random(1,6); //keep between 1 and 5
final int N_CARS = 6 + DIFFICULTY;
final int CAR_HEIGHT = 24;
final int FROG_SIZE = 24;
int score = 0;
Car[] cars;
Frog frog;
void setup() {
size(600,480);
background(255);
frog = new Frog();
cars = new Car[6 + DIFFICULTY];
for (int i=0; i<cars.length; i++) {
int carLength = (int)random(40,101);
cars[i] = new Car(carLength, CAR_HEIGHT, 15 + i*30);
}
}
void draw() {
background(255);
lanes();
for(int i = 0; i <= cars.length; i++) {
cars[i].displayTheCarMove(); /*THIS IS WHERE I GET THE ERROR. BUT ABOVE THERE IS A SIMILAR LINE OF CODE AND THAT WORKED FINE. */
}
frog.display();
}
void keyPressed() {
frog.move();
}
class Car {
float cWidth, cHeight;
float centerX, centerY;
float speed;
int shade;
Car(float cL, float cH, float lane) {
cWidth = cL;
cHeight = cH;
centerX = random(cL/2, width - cL/2);
centerY = constrain(centerY, 3 + cH/2, (6 + DIFFICULTY)*LANE_HEIGHT);
}
void displayTheCarMove() {
display();
carMove();
}
void carMove() {
centerX += speed;
if((centerX <= cWidth/2) || (centerX >= width - cWidth / 2)) {
speed *= -1;
}
}
void display() {
rectMode(CENTER);
noStroke();
fill((int)random(201));
rect(centerX, centerY, cWidth, cHeight);
}
}
Thank you in advance.
1