Reputation: 605
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
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
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
Reputation: 494
Your solution is very simple,Divide your condition in to steps:
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
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