【问题标题】:iterate loop at least 1000 times循环至少 1000 次
【发布时间】:2016-02-28 02:43:29
【问题描述】:

我有一个 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 时就破掉它。

标签: java loops iteration


【解决方案1】:
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
  }
}

【讨论】:

    【解决方案2】:
    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;
    }
    

    【讨论】:

      【解决方案3】:

      带有附加条件和计数器:

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-23
          相关资源
          最近更新 更多