java - 仅在第一个循环中检查条件,在其余循环中执行一些代码

标签 java for-loop conditional-statements

有没有办法只在 for 循环的第一个循环中检查条件,如果条件被评估为真,则在其余循环中执行一些代码?我有一个 for 循环和其中的两个基本条件,只需要在第一个循环中检查。如果其中任何一个为真,那么一段或另一段代码将在所有其他周期中执行。我无法在其他周期中检查这些条件,但第一个,因为两者都是真实的,这不是我需要的((

    public void someMethod() {
    int index;
    for (int j = 0; j < 10; j++) {
        if (j == 0 && cond1 == true && cond2 == true) {
            methodXForTheFirstCycle();// this method will change cond2
            methodXForTheRestCycles();// not the right place to put it
        } else if (j == 0 && cond1 == true) {// and cond2 == false
            methodYForTheFirstCycle();// this method will change cond2
            methodYForTheRestCycles();// not the right place to put it
        }
    }
}

最佳答案

我建议你稍微展开你的循环。

if (cond1)
   // j == 0
   if (cond2) 
        methodXForTheFirstCycle();
   else 
        methodYForTheFirstCycle();
   cond2 = !cond2;

   for (int j = 1; j < 10; j++) {
     if (cond2)
        methodXForTheRestCycle();
     else 
        methodYForTheRestCycle();
     cond2 = !cond2;
   }
}

关于java - 仅在第一个循环中检查条件,在其余循环中执行一些代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14042935/

相关文章:

java - 小程序请求不延长 session 实时

python - 如何通过 for 循环中的 for 循环将列表 append 到数据帧

c++ - `if ( __some_bool__ != NULL )` 的行为如何?

R - 根据向量中的任何值编写条件语句

python - 在 python 中标记的多个和或条件

java - 如何从 HttpServlet 访问同一个 bean 实例?

java - 图像IO奇怪的行为重置输入流

java - 通过高级客户端写入elasticsearch - 在文档上设置时间戳

c# - 一维数组中的条件语句

python - 向量中的三重 for 循环