2016-08-04 133 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 
}