我需要根据循环控制变量确定要采取的操作

时间:2016-12-08 21:27:15

标签: java for-loop

在for循环中,我想根据循环控制变量确定要采取的操作,从我的评论中可以看出它很棘手

   public void someFunction(int numberOfReps)
   {
     for (int i = 0; i < numberOfReps; i++)
     {
        //if it's first execution; do that, but also do it if it's fourth or eights etc into infinity
        //if it's second execution; do that, but also do it if it's fifth or ninth etc into infinity
        //if it's third execution; do that, but also do it if it's sixth or tenth etc into infinity
     }
   }

3 个答案:

答案 0 :(得分:0)

使用模数运算符%4:

0%4为0,4%4为0,8%4为0 ...所以它满足第一个条件

1%4为1,5%4为1 ...因此它满足第二个条件 ... ..

我相信你可以弄清楚剩下的。

提示:使用 continue 关键字跳过执行其余循环。

答案 1 :(得分:0)

对于您需要检查的每个条件,您必须有某种条件声明。

您可以在Java中使用多个条件和OR运算符exports.config = { jasmineNodeOpts: { grep: '@smoke', } }; 来确定是否满足其中一个条件。另外值得注意的是,您可以使用AND运算符||来确定是否已满足这两个条件。

例如:假设您需要确定数字是否等于1或是3的倍数(3,6,9,12等)

&&

答案 2 :(得分:0)

是这样的吗?

   public void someFunction(int numberOfReps)
   {
     for (int i = 1; i < numberOfReps; i++)
     {
        if(i==1 || i%4==0){
           doFirst();
        //if it's first execution; do that, but also do it if it's fourth or eights etc into infinity
        }else if(i==2 || i%5==0){
           doSecond();
        //if it's second execution; do that, but also do it if it's fifth or ninth etc into infinity
        }else if(i==3 || i%6==0){
           doThird();
        //if it's third execution; do that, but also do it if it's sixth or tenth etc into infinity
        }
      }
    }