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 › How to name a new Object inside a for() loop
Page Index Toggle Pages: 1
How to name a new Object inside a for() loop ? (Read 671 times)
How to name a new Object inside a for() loop ?
Dec 6th, 2009, 7:41am
 
I want to create a new Object of the class "Meme" inside a for-loop.
I have to find a name for every new Object, so I decided to create the name based on the "i" of the loop.
nf() for translating the int i to a String.

But then it gives an Error: "Duplicate local variable Name".
What can I do to make him accept the given name of the Object?


for(int i = 0; i<linkliste.length; i++){
   if(linkliste[i] != null){      
     String Memename = nf(i,3);
     
    Meme Memename = new Meme(linkliste[i]);
 }
 }
Re: How to name a new Object inside a for() loop ?
Reply #1 - Dec 6th, 2009, 8:35am
 
> I decided to create the name based on the "i" of the loop
You have to use an array (or an ArrayList) :

Code:
// declare the array of Meme objects
Meme[] memes;

// setup the array
memes = new Meme[linkliste.length];

// fill the array
for (int i = 0; i < linkliste.length; i++) {
 Meme memes[i] = new Meme(linkliste[i]);
}


You can shorten declaration and setup in one line :
Code:
Meme[] memes = new Meme[linkliste.length]; 



See the reference for further array processing (append(), etc.) or how to do handle objects collections with an ArrayList object.
Re: How to name a new Object inside a for() loop ?
Reply #2 - Dec 6th, 2009, 8:44am
 
If you want to create multiple objects in a loop it's usual to put them into a container object (e.g. Array, ArrayList etc.).

Code:
Ball b[];
int numBalls = 3;

void setup() {
size(420, 400);

// Instantiate balls array
b = new Ball[numBalls];
//populate it:
for (int i=0; i<numBalls; i++) {
b[i] = new Ball();
}
}


Then if you need to do something with the objects later you can just iterate over the container...
Re: How to name a new Object inside a for() loop ?
Reply #3 - Dec 6th, 2009, 9:06am
 
Ca marche!
Thank you!
Cheesy
Page Index Toggle Pages: 1