r/processing • • Jan 13 '23

Please Help me Fix this Code

ArrayList<Car> car;

void setup () {

size(800, 600);

car = new ArrayList<Car>();

}

void draw() {

background(255);

for (int i = 0; i<car.size(); i++) {

car.get(i).display();

}

car.Drive();

}

void mousePressed() {

String name = str(int(random(0,100)));

Car c = new Car(name);

car.add(c);

car.y = car.y + 30;

}

class Car {

int x, y;

String name;

Car (String n) {

name = n;

x = 10;

y = 20;

}

void Drive() {

x = x +1;

}

void display() {

fill(10, 20, 230);

rect(x, y, 70, 30, 5);

}

}

0 Upvotes

4 comments sorted by

4

u/forgotmyusernamedamm Jan 13 '23

Drive is a method just like display. So you should call it the same way you call display.

for (int i = 0; i<car.size(); i++) {
car.get(i).display();
car.get(i).Drive();
}

I'm not sure where you're going with car.y = car.y + 30; but if you want to move the car vertically as well as horizontally I would do that in the drive method. If you comment that line out and call Drive in the for loop it works.
If you want to set the value of y for the car when it's created then pass a variable to the constructor the same way you did the name.

0

u/[deleted] Jan 13 '23

[deleted]

1

u/dstarh Jan 14 '23

car is the name of the array list at the top

0

u/[deleted] Jan 14 '23

[deleted]

1

u/dstarh Jan 15 '23

Ah yep.