tags:

views:

90

answers:

5

hi

in java, how can we execute an instruction only one time in a do while loop

do{
    int param;

    //execute this onty one time (depends of param)
    //other instructions instructions

}while(condition)

thank you

+2  A: 

How about:

// one-time-code here

do
{
}
while ( condition );
Bob Kaufman
no i can because i have a for loop before the while loop so same probleme in the for loop and the instruction depends of a parametere exists inside the while loop
tuxou
Please show a larger sample of your code that includes said for-loop. It will allow us to provide more specific answers. :)
Bob Kaufman
Unfortunately, I think this is too simplistic of a solution (although, his question doesn't make it clear). See my answer.
JasCav
@Jason: Agreed, however based on what was asked, this is the simplest answer. Based on OP's comment, I'm hoping we're going to get a clearer picture of the question shortly.
Bob Kaufman
+1  A: 

Putting a statement outside of any loops will cause it to only be executed once every time the method is called.

Ignacio Vazquez-Abrams
A: 

Move the statement you want to execute only once outside the while loop.

Paul Hankin
+4  A: 

Putting the statement you want to execute only once is one way of doing it, but, of course, that assumes that the statement comes at the end or beginning of the loop, and doesn't depend on the conditions of what goes on in the loop (either before or after). If you have something like this:

do {
  // do some stuff
  // one time condition
  // do some more stuff
} while(condition);

you won't easily be able to pull that information outside of the loop. If this is your problem, my suggestion would be to place some sort of condition around the one-time statement(s) and update the condition when the statement has run. Something like this:

boolean hasRun = false;
do {
  // do some stuff
  if(!hasRun) {
    // one time condition
    hasRun = true;
  }
  // do some more stuff
} while(condition);
JasCav
I think of this but i wonder if it exists another way to do it
tuxou
+1  A: 

Assuming you want to keep the code inside the loop (other posters have suggested the obvious solution of moving the code outside!), you could consider using a flag to execute it only once:

boolean doneOnce=false;

do{

  if (!doneOnce) {

    \\execute this only one time

    doneOnce=true;
  }

  \\other instructions instructions

} while (condition)

Could be a useful construct if for example you had other instructions in the loop before the once-only code.

mikera