迭代循环至少 1000 次

iterate loop at least 1000 times

我有一个 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 次。我该怎么做?

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
  }
}

有附加条件和计数器:

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

你的解决方法很简单,把你的情况分成几步:

  • 声明一个计数器并在每次迭代中更新该计数器。
  • 使用 if 语句检查 mycondition
    • 如果我的条件为真,则应用另一个 if 条件来检查计数器是否已达到 1000。 如果两个条件都成立,那么才更新你的结束变量

所以你的整体解决方案变成:

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

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