2016-08-04 132 views
-5

我有一個循環迭代等於數組的長度,在這個循環內我有一個方法做一些處理,並有內部的if-else結構。我想,如果某些條件是真的,那麼重新循環整個循環,否則繼續。 提供最低工作代碼。 fp.factprocess的返回INT從一個循環中的語句if語句

for(int xx=0;xx<temp.length;xx++) 
    { 
    rule=temp[xx][1]; 
    cons=temp[xx][2]; 
    fp.factprocess(fact, rule, vars, cons); 
    } 

內容就像

if(condition==true) 
    make xx = 0 in the parent loop 
else 
continue 

我不知道該怎麼做呢,我用return語句,但它必須是到底,不能在如 - 塊。

+0

好的....感謝分享。 – specializt

+1

[什麼是XY問題?](http://meta.stackexchange.com/a/66378) – flakes

回答

3

從條件測試中返回一個布爾值。如果布爾值爲true,則將循環中的xx設置爲-1(將遞增爲0)。

for(int xx=0;xx<temp.length;xx++) 
    { 
    rule=temp[xx][1]; 
    cons=temp[xx][2]; 
    boolean setXXtoZero = fp.factprocess(fact, rule, vars, cons); 
    if(setXXtoZero) xx=-1; 

    } 

fp.factprocess:

return condition; 
+1

您可能想要將最後一部分重寫爲:'return condition;' – Stultuske

1

是的,在if塊中可以有return語句。

public int getValue(int val){ 
    if (value == 5){ 
    return value; 
    } 
    else{ 
    return 6; 
    } 
} 

例如,是有效的Java代碼。

public int getValue(int input){ 
    if (input == 5){ 
    return input; 
    } 
} 
,另一方面

,是不是,因爲你如果輸入不等於5不返回任何東西,但該方法要麼返回一個int,或拋出異常。

這可能是你的問題所在:你需要爲所有可能的場景提供一個return語句。

+0

謝謝我會試一試並更新你,它是否必須在每種可能的情況下返回?因爲我不想返回else-block –

+0

中的任何東西,所以您必須返回某個內容,或拋出異常來中斷該方法。最好是返回一個值 – Stultuske

1

如果你想修改循環的xx變量,我建議在你的factprocess方法中返回一個布爾值。

for (int xx = 0; xx < temp.length; xx++) { 
    rule = temp[xx][1]; 
    cons = temp[xx][2]; 
    boolean shouldRestart = fp.factprocess(fact, rule, vars, cons); 
    if (shouldRestart) { 
    xx = 0; 
    } 
} 
1

通行證xxfactprocess()並分配回xx

for(int xx=0;xx<temp.length;xx++) 
    { 
    rule=temp[xx][1]; 
    cons=temp[xx][2]; 
    xx = fp.factprocess(fact, rule, vars, cons, xx); 
    } 

factprocces()

if (condition == true) { 
    return 0 
} else { 
    return xx 
}