开发者

execute an instruction only one time in a do while loop in java

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 instructio开发者_StackOverflowns

}while(condition)

thank you


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);


How about:

// one-time-code here

do
{
}
while ( condition );


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


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.


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


Add break:

do {
        int param;

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

        break;

    } while(condition);


Trying to answer exactly what you asked:

bool ranOnce = false;
do{
    int param;

    if (param == SOMECONDITION and !ranOnce){
      doWhatYouWant();
      ranOnce = true;
    }
    //other instructions instructions

}while(condition)

So there you have it, run something only once depending on param.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜