Reputation: 4032
I've created 3 variables
radio1 radio2 radio3
is it possible to use a for loop and from a String called "radio" to add the counter in the end in order to get the variable?
for instance something like this
for(i=1;i<=3;i++)
if(("radio" + i).method())
do something
thanks in advance
Upvotes: 3
Views: 514
Reputation: 9016
It looks to me like you want to use a Dictionary or similar data structure, which lets you store objects indexed by, for example, a string.
EDIT
As several people noted, HashMap
is a more modern and better alternative.
Upvotes: 1
Reputation: 66323
The most convenient way is to use an intermediate array like this:
Radio radio1, radio2, radio3;
for(Radio radio: Arrays.asList(radio1, radio2, radio3))
if( radio.method() )
doSomething();
The java.util.Arrays
is provided by the JDK.
This works. But please think about it, how many times you really want three separate Radio
instances vs. how many times you are not interested in one of them but in all of them. In the later case put the three instances into a Collection
or into an array right from the start and forget about the three individual instances.
Upvotes: 0
Reputation: 35505
You can use a Radio object and use arrays instead:
Radio[] radios = new Radio[] {radio1, radio2, radio3};
for(i=0;i<3;i++)
if(radios[i].method())
do something
If you want to access variable by forming their names, you can also use Java's reflection API. But it is an expensive operation and is not advisable in general.
Upvotes: 7
Reputation: 8452
You should be using an array
so you can easily iterate over all of them.
You could also play with Lists if you do not know how many items there wil be.
Upvotes: 0