2017-05-02 14 views
0

Gotoを避けなければなりません。しかし、あなたが醜いコードなしでそれを避けることができない場合があります。「ループ後にコードを実行しないでください」

ループ内の式は、真である、ループを破る必要があります。

は、このケースを考えてみましょう。

ループ内の式が常にfalseの場合、ループ終了後、コードを実行する必要があります。

gotoなしでこれを行うには良い方法がありますか?

for (int x = 0; x < input.length; ++x) 
    if (input[x] == 0) goto go_here; // this is pseudocode. goto is not allowed in java 
// execute code 
go_here: 

私のソリューションはこれです:

both: 
do { 
    for (int x = 0; x < input.length; ++x) 
     if (input[x] == 0) break both; 
    // execute code 
} while(false); 

別の解決策はこれです:

boolean a = true; 
for (int x = 0; x < input.length; ++x) 
    if (input[x] == 0) { a = false; break; } 
if (a) { 
    // execute code 
} 

(後藤と同様に)別の非効率的な解決策はこれです:

try { 
    for (int x = 0; x < input.length; ++x) 
     if (input[x] == 0) throw new Exception(); 
    // execute code 
} catch(Exception e) {} 
+0

あなたは正確に何を言おうとしていますか? 'goto'文はJavaでは許されません。しかし、それは予約語です。 – Logan

+0

最初のケースでは、break、loopsを実行してコードを実行しないためです。 2番目のケースでは、ループは正常終了し、コードが実行されます。 – Chameleon

+3

ジョーになるの? http://thedailywtf.com/articles/do-while-false – clcto

答えて

1

を別の解決策は以下のとおりです。

both: { 
    for (int x = 0; x < input.length; ++x) 
     if (input[x] == 0) break both; 
    // execute code 
} 

はブロック文は文ですので、あなたはそれをラベルを与えることができます。

6

入れ方法のあなたの状態:

void yourMethod() { 
    if (yourCondition(input)) { 
    // execute code. 
    } 
} 

boolean yourCondition(int[] input) { 
    for (int i : input) { 
    if (i == 0) return false; 
    } 
    return true; 
} 

それとも、あなたがIntStream使用したい場合:ここで

if (IntStream.of(input).noneMatch(i -> i == 0)) { 
    // execute code. 
} 
関連する問題