We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › "for" loop to create object instances
Page Index Toggle Pages: 1
"for" loop to create object instances (Read 685 times)
"for" loop to create object instances
Aug 16th, 2009, 10:06am
 
say i have a class called "Car".

i could declare some cars like this:

Code:
Car myCar1 = new Car();
Car myCar2 = new Car();
Car myCar3 = new Car();
Car myCar4 = new Car();
Car myCar5 = new Car();
...


What if i want to create many many Cars using a for() loop or something? what is the right way to have the loop append a number to the string "myCar" for each car i want to create?

Additionally, say i already have 100 or so Cars, each named myCar00, myCar01,... all the way to myCar99. What would be the right way to have a for() loop reference a specific car based on the value of its internal index ("i" or example)?

I hope my questions make sense.
Re: "for" loop to create object instances
Reply #1 - Aug 16th, 2009, 10:28am
 
See [] (array access) and array functions in reference.
You do:
Code:
Car[] myCars = new Car[CAR_NB];
for (int i = 0; i < CAR_NB; i++)
{
myCars[i] = new Car();
}

Note you declare the array, then each element, with slightly different syntaxes.
Re: "for" loop to create object instances
Reply #2 - Aug 16th, 2009, 11:11am
 
ahhhh ok... duh. so it wouldn't create myCar1, myCar2,..... but it creates myCar[1], and myCar[2],... gotcha. Thanks.
Page Index Toggle Pages: 1