# Repeat a bit of code? [closed]

I want to complete a task, which assigns the variable randomButton a value. At the end, I want to check the value of randomButton If it is something I don't like, I want to re do the task where I assign randomButton a value.

I want to do this task:

        int i = rng.nextInt(4); //Find random button from between 1-4
randomButton = buttons.get(i);
buttonBackground = randomButton.getBackground();
Log.v(TAG, "In the do");


and if

buttonBackground.equals(R.drawable.redcircle)


I want to try and do the task again. How do I achieve this...?

I have tried:

do {
int i = rng.nextInt(4); //Find random button from between 1-4
randomButton = buttons.get(i);
buttonBackground = randomButton.getBackground();
Log.v(TAG, "In the do");
}while(buttonBackground.equals(R.drawable.redcircle));


But, for some reason, the code in the do part still executes even if buttonBackground equals R.drawable.redcircle. Also, can I make buttonBackground a string so that I can log it?

By the way, buttons is an arraylist with different image button objects. I want to see if the background of that imagebutton (randomButton) is redcircle. If it is, I want to go through the code again. If it isn't, thats great, and I can continue.

• I think there is a confusion in your question. You say that if buttonBackground.equals(R.drawable.redcircle), you want to try and do the task again. But then you say that "for some reason, the code in the do part still executes even if buttonBackground equals R.drawable.redcircle". Well, wasn't that exactly what you wanted? – MAnd Nov 29 '15 at 0:40
• Please limit your posts to a single question. If you have many questions, please create many question posts. – Vaillancourt Dec 2 '15 at 12:04

If I'm understanding you correctly, then this is my suggestion...

Create a function that returns a bool value. True if succeeded, false if not. Have that function run itself until it produces true. This is called a recursive function.

Ex in slight psudo-code:

bool foo()
{
bool success = myfunction();
if not success
foo();
return true;
}