3

I am using a Do While loop but i have to test whether that condition is met half way through the loop so that if it is met it will skip that part. Is there an efficient way of doing this?

e.g. I currently have something like this:

do {
    method1;
    if (!condition) 
        method2;
} while (!condition);

EDIT: I apologise, i don't think i made it clear in the first place. The condition starts as being false, and at some point during the loop one of the methods will set the (global) "condition" to true at which point i want the loop to immediately end. I just think it's messy having to test the ending condition of the loop within it and was wondering if there was anything obvious i was missing.

4

7 に答える 7

2

「条件」がほとんどの場合(多くのうちの1つ)満たされないため、あなたが探しているのは、この追加の効率テストを避けていると思います...この最適化は、method1で実際に行われていることをさらに深く掘り下げることによって行うことができます。 method2(またはそれらが処理しているデータ)を使用して、ループの外側に最初の「偽のステップ」を追加します。これにより、method2の処理が初めて無効になります。このようになります:

prepare_for_loop_entering
do {
   method2
   method1;
} while (!condition);
于 2012-09-22T13:25:57.367 に答える
2

メソッドに関する詳細情報を提供してください。method1/2 から条件を返すことができる場合は、次を試してください。

do {
    method1;
} while (!condition && !method2)

または、参照渡しでメソッドが常に true を返す場合:

while (method1 && !condition && method2 && !condition);

また:

while (!method1 && !method2);

編集:場合:

public boolean method1/2 { ... logic ... ; condition = true; return condition;}

あなたが何をするかにほとんど依存しません。

于 2012-09-22T13:19:27.677 に答える
0

以下のコードはどうでしょう。

if(condition)
break;
于 2012-09-22T13:05:26.660 に答える
0

これはどうですか:

 while (!condition) {
   method1;
if(!condition)
   method2;
}
于 2012-09-22T13:07:16.943 に答える
0

ループの最も一般的な形式を使用します。

while (true)
{
    method1;
    if (!condition) break; 
    method2;
} 

さらなる説明

条件「条件」を使用した while ループは、次のようになります。

while (true)
{
    if (condition) break;
    method1;
    method2;
}

do-while は次のようになります。

while (true)
{
    method1;
    method2;
    if (condition) break;
}

どちらも必要ないため、上記のコードです。

于 2013-12-23T18:38:00.823 に答える
0

conditionあなたがそれを参照するすべての場所で同じである場合

do {
    method1;
    method2;
} while (!condition);

while ループのように、 true に設定するとすぐにtrue に設定しない限り、condition常に false になります ( true になります)。!conditionmethod1;break;method1;

于 2012-09-22T13:04:34.040 に答える
0

これはどう:

method1;
while (!condition) {
   method2;
   method1;
}
于 2012-09-22T13:16:14.417 に答える