Sandy.Arv
Sandy.Arv

Reputation: 605

iterate loop at least 1000 times

I have a while loop which exits when some condition met is true. i.e.,

boolean end = false;
while(!end){
    //Some operations based on random values
    //if statement to check my condition, and if it is met, then
end = true; //exits loop
}

Now since my program executes based on random numbers generated, sometimes the loop runs > 1000 times and some times < 1000 times(like 200, 300 etc). I want this code to iterate at least a 1000 times before checking the condition and exiting the loop. How do I do that?

Upvotes: 2

Views: 3711

Answers (4)

nano_nano
nano_nano

Reputation: 12523

With an additional condition and a counter:

boolean end = false;
int count = 0;
while(!end){
  count++;
  //Some operations based on random values
  //if statement to check my condition, and if it is met, then
  if (count>1000){
    end = true; //exits loop
  }
}

Upvotes: 2

cssGEEK
cssGEEK

Reputation: 1014

boolean end = false;
int counter =0;


 while(!end){
    counter++;
        //Some operations based on random values
        //if statement to check my condition, and if it is met, then
    end = true; //exits loop
    if(counter<1000)
         continue;
}

Upvotes: 3

Haseeb Anser
Haseeb Anser

Reputation: 494

Your solution is very simple,Divide your condition in to steps:

  • Declare a counter and update that counter in every iteration.
  • Check mycondition using if statement
    • if mycondition is true apply another if condition to check if the counter has reached 1000. if both conditions become true,only then update your end variable

so your overall solution become:

boolean end = false;
int count = 0;
while(!end){
  count++;
  //Some operations based on random values

 if(mycondition){
    if (count>1000)
     end = true;
  } //exits loop
}

Upvotes: 2

Adil Shaikh
Adil Shaikh

Reputation: 44740

int numberOfIteration = 0;
while(!end){
  numberOfIteration++;
    //Some operations based on random values
    //if loop to check my condition, and if it is met, then
  if(numberOfIteration > 1000){
   end = true; //exits loop
  }
}

Upvotes: 3

Related Questions