0

how can I access declared variables using counter, in a loop, like this:

declared variables:

Button square0, square1, square2, square3, square4, square5, square6,
        square7, square8, temp;

accessing them with a loop like this:

for (int i = 0; i < 9; i++) {
    (Button) ("square"+i).setBackgroundResource();
1
  • This is really bad practice in any language. Commented Apr 20, 2012 at 19:25

3 Answers 3

3

You can't without resorting to some really dubious magic (I don't even think you can do this with reflection in Java).

Use an array instead.

Sign up to request clarification or add additional context in comments.

Comments

2

It is very easy...

Button[] btnArray = new Button[10]; 
 //assign all squares to the array 
btnArray[0] = square1;
for(Button btn : btnArray){
btn.setBackGroundResource();
}

or even better use a List like

List<Button> myBtnList = new ArrayList<Button>();
myBtnList.add(square1);

add till all buttons are added then use the for each loop as illustrated above.

1 Comment

btnArray.add(square); won't work with an array. Use btnArray[0] = square;
0

As others have mentioned this is bad practice in any programming language. If you want to access a list of things (in your case Buttons), you should use a List or an Array.

Here is an example using an ArrayList of Buttons:

List<Button> buttonList = new ArrayList<Button>();

Button button1 = new Button();
Button button3 = new Button();
Button button2 = new Button();

buttonList.add(button1);
buttonList.add(button2);
buttonList.add(button3);

// How to get a button out
for(int i = 0; i < buttonList.size(); i++)
    myButton = buttonList.get(i);
    // Do something with myButton here.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.