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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With