【问题标题】:How to make a do while loop restart after certain amount of iterations如何在一定数量的迭代后重新启动循环
【发布时间】:2020-01-25 06:57:39
【问题描述】:

我有一个 do while 循环

int maxItter = 20;
int index = maxItter;
do {
    index --;
    int itterNum = maxItter-index;

    //stuff

} while (index > 0);
index = index + 1;

其中maxItter 等于最大迭代次数,itterNum 是 do while 循环开启的当前迭代。

20 次迭代后,我希望 'itterNum' 在 0 处重新开始

我该怎么做?

【问题讨论】:

  • 你可以用另一个循环包裹你的循环
  • 那不是无限循环吗?

标签: java loops iteration do-while


【解决方案1】:

您可能只想使用模数。也可以用 for 循环来简化这个

int maxIter = 20;
for (int index = 0;; index++) {
    int iterNum = index % maxIter;
    //stuff
}

【讨论】:

    【解决方案2】:

    我希望你的问题是正确的。在这种情况下,您将获得无限循环:

    public static void main(String[] args) {
        int maxItter = 20;
        int index = maxItter;
        do {
            index --;
            int itterNum = maxItter-index;
    
            //stuff
    
            if (itterNum == 20) {
                index = 20;
            }
            System.out.println(itterNum + " " + index);
        } while (index > 0);
        index = index + 1;
    }
    

    【讨论】:

      【解决方案3】:

      可能有 n 种方法,

      public class Main {
          public static void main(String[] arg) {
              int maxItter = 20;
              int index = maxItter;
              // how many times you want to restart the loop
              int numberOfRestart = 10;
              do {
                  index --;
                  int itterNum = maxItter-index;
                  if(index == 0) {
                      index = maxItter;
                      numberOfRestart --;
                  }
                  if(numberOfRestart == 0) {
                      break;
                  }
              } while (index > 0);
              index = index + 1;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-03
        • 2015-03-14
        • 2018-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多