Java,如果条件为false,则重复If语句

时间:2015-06-05 13:14:33

标签: java arrays if-statement

简化,我基本上都有这样的if语句:

if(A[random]==1)
    A[random]=0;
else 
    continue;

现在我知道'继续'是for循环语句,这不会起作用,但是我想要一些其他的东西,如果确实其他(基本上条件是假的)被激活它重复第一个if(A [random] == 1)语句。

5 个答案:

答案 0 :(得分:7)

您可以改为使用while语句:

while (A[random] != 1) {
    A[random] = 0;
    // generate a new random...
}

答案 1 :(得分:1)

您可以尝试下面的递归代码,看看这个解析是否是您的查询

public class Test {


 public void continueIf(){
    if(A[random]==1)
        A[random]=0;
    else {
        continueIf();
    }
 }

 public static void main(String[] args) {
    new Test().continueIf();
 }
}

请注意,如果条件不满足,则会导致stackoverflower错误。这也取决于JVM内存的大小。有关stackoverflow错误的详细信息,请查看此link

答案 2 :(得分:1)

if / Else语句本身不能循环遍历数组。我建议将它粘贴在For循环或While循环中。循环将搜索数组,if / else语句将检查索引是否提供了条件。我也会摆脱其他的。你真的不需要那个部分只是if。

最基本的例子中的for循环看起来像这样:

    for(var i = 0; i < SIZE; i++)
        {
           if (A[i] == 1)
                 A[i] = 0;
        }

SIZE将是数组的大小

答案 3 :(得分:1)

random = ...;  // get first random number
while (A[random] != 1) {
    random = ...; // get new random number
}
A[random] = 0;  // now is 1, switch it to 0

答案 4 :(得分:1)

这应该工作。其他答案描述了while和recursion所以我 还添加了一个do while循环。

 do{
    //generate the  random number
    }while(A[random]!=1)//The loop iterates till the condition A[random]!=1 is satisfied
    A[random]==0;//changing the bit to 0

请注意,如果阵列中没有bit =1,则此解决方案将失败,因为您正在随机生成索引。 因此,如果数组没有element =1,那么它会不断重复检查索引并生成infinite loop

希望它有所帮助。快乐的编码!!

相关问题