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 › Define dynamic variable name
Page Index Toggle Pages: 1
Define dynamic variable name (Read 1072 times)
Define dynamic variable name
Sep 20th, 2007, 10:12pm
 
Hi,

I'm trying to dynamically create variables by adding a string and an integer to define it's name.
I want to do it with a "for" loop because I don't know how many variables I will need.

Let's say I need 100 variables of type "int", I don't want to manually write :
int Something1;
int Something2;
int Something3;
...
int Something100;

Here's my logic when using processing :
----------------
int quantity= 5;
for (int num = 0; num < quantity; num++) {
 int ["Something" + num];
}
----------------

Problem is, this doesn't work. I don't know how to make it as a variable by adding a dynamic number.

Anyone knows the solution? Ideas?

Thanks
Steven


Re: Define dynamic variable name
Reply #1 - Sep 20th, 2007, 11:50pm
 
You can't do dynamic variable names in processing. That's a flash-ism.

What you can do, is arrays, which will get you the same end result:

Code:
int[] myArray;
myArray=new int[100]; //myArray now has 100 integers.
myArray[0]=12;
myArray[1]=23;
for(int i=2;i<100;i++)
{
myArray[i]=i; //loop through the remaining 98 elements.
}
Re: Define dynamic variable name
Reply #2 - Sep 20th, 2007, 11:52pm
 
hi steven,

I'm not sure, but I think this concept does not exist in Java.

A much cleaner and easier way would be to use an array. Instead of having
 int Something1;
 int Something2;
 int Something3;
 ...
 int Something100;
you would have something like this:
 int[] something = new int[100];
To access an int in this array, use this syntax:
something[theNumberYouWant] = 3;

Reading this will make it clear:
http://processing.org/learning/basics/array.html
Re: Define dynamic variable name
Reply #3 - Sep 21st, 2007, 12:01am
 
Thanks guys!

I'll give it a try!
Page Index Toggle Pages: 1