[英]Java, repeat If statement if the condition was false
簡化后,我基本上有一個if語句,例如:
if(A[random]==1)
A[random]=0;
else
continue;
現在,我知道“ continue”是for循環語句,將不起作用,但是在其他情況下我想要一些東西,如果確實的話,else(基本條件為假)被激活,它將重復第一個if(A [random] = = 1)聲明。
您可以改用while
語句:
while (A[random] != 1) {
A[random] = 0;
// generate a new random...
}
您可以嘗試下面的遞歸代碼,看看此解析是否是您的查詢
public class Test {
public void continueIf(){
if(A[random]==1)
A[random]=0;
else {
continueIf();
}
}
public static void main(String[] args) {
new Test().continueIf();
}
}
請注意,如果條件不滿足,則將導致stackoverflowerror。 這也取決於JVM內存的大小。 檢查此鏈接以獲取有關stackoverflow錯誤的更多詳細信息。
if / Else語句本身無法遍歷數組。 我建議將其粘貼在For循環或While循環中。 循環將搜索數組,並且if / else語句將檢查索引是否提供了所提供的條件。 我也將擺脫其他。 您實際上只需要if。
最基本的示例中的for循環如下所示:
for(var i = 0; i < SIZE; i++)
{
if (A[i] == 1)
A[i] = 0;
}
SIZE將是數組的大小
random = ...; // get first random number
while (A[random] != 1) {
random = ...; // get new random number
}
A[random] = 0; // now is 1, switch it to 0
這應該工作。其他答案已經描述了while和遞歸,所以我也添加了一個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
。
希望對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.