我有一个while循环,当某些条件满足时退出。即,
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
}
既然我的程序基于生成的随机数执行,有时循环运行> 1000次有时< 1000次(如200,300等)。我希望此代码在检查条件并退出循环之前至少迭代1000次。我该怎么做?
答案 0 :(得分:3)
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
}
}
答案 1 :(得分:3)
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;
}
答案 2 :(得分:2)
附加条件和计数器:
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
}
}
答案 3 :(得分:2)
您的解决方案非常简单,将您的条件分为以下步骤:
所以你的整体解决方案成为:
boolean end = false;
int count = 0;
while(!end){
count++;
//Some operations based on random values
if(mycondition){
if (count>1000)
end = true;
} //exits loop
}