迭代循环至少1000次

时间:2015-11-25 10:39:50

标签: java loops iteration

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

4 个答案:

答案 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)

您的解决方案非常简单,将您的条件分为以下步骤:

  • 声明一个计数器并在每次迭代中更新该计数器。
  • 使用if语句检查mycondition
    • 如果mycondition为true,则应用另一个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
}