3

条件がtrueと評価された場合、forループの最初のサイクルでのみ条件をチェックし、残りのサイクルでいくつかのコードを実行する方法はありますか?forループとその中に2つの基本的な条件があり、最初のサイクルでのみチェックする必要があります。それらのいずれかが真の場合、他のすべてのサイクルで1つまたは別のコードが実行されています。他のサイクルではこれらの条件を確認できませんが、最初のサイクルは両方とも真であり、必要なものではないためです((

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

4 に答える 4

2

ループを少しアンロールすることをお勧めします。

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;
   }
}
于 2012-12-26T16:27:24.573 に答える
1

あなたのコードは何もしないので、私は少し混乱していますj!=0-それで、なぜループがまったくないのですか?

ループを分割します。i==0最初のメソッドを呼び出すものを引き出してから、i=1 .. 9

これはあなたがあなたの説明によって意味すると私が思うものです:

public void someMethod() {
  int index;
  if (cond1) {
    if (cond2) {
      methodXForTheFirstCycle();
      for (int j = 1; j < 10; j++) {
        methodXForTheRestCycles();
      }
    } else {
      methodYForTheFirstCycle();
      for (int j = 1; j < 10; j++) {
        methodYForTheRestCycles();   
      }
    }
  }
}
于 2012-12-26T16:10:06.627 に答える
0

新しいフラグ(ブール値)を使用してみてください。また、以下のようにブール値をtrueと比較する必要はありません。

public void someMethod() {
  int index;
  boolean firstConditionSuccess = false;
  for (int j = 0; j < 10; j++) {
    if (j == 0 && cond1 && cond2) {
        methodXForTheFirstCycle();
        firstConditionSuccess = true;
    } else if (j == 0 && cond1) {// and cond2 == false
        methodYForTheFirstCycle();
        firstConditionSuccess = true;
    }
    if(firstConditionSuccess ){
       methodYForTheRestCycles();
    }
 }
}
于 2012-12-26T16:21:14.660 に答える
0

私があなたが正しく望んでいることを理解しているなら、あなたができることは、2つの条件を一度チェックし、それらが失敗した場合は中断することです。それらが成功した場合は、フラグをtrueに設定して、後続の反復でチェックをバイパスするようにします。

于 2012-12-26T16:03:48.237 に答える