Rya*_*axe 0 java for-loop infinite-loop while-loop
所以我正在写一个程序,有人从牌组中取出牌.所以我写了一个while循环,循环并检查是否有超过4个随机创建的卡,如果有,更改卡.
这是我的代码:
String card = (int)Math.ceil(Math.random() * 13) + " ";
String[] used2 = used.split(" ");
//used is a String like "12 3 7 8 4 ... # etc" such that it is all the previously drawn cards.
boolean checking = true;
boolean isIn = false;
int in = 0;
int check = 0;
while(checking){
for(int q = 0; q < used2.length; q++){
check += 1;
if(card.equals(used2[q] + " ")){
in += 1;
if(in == 4){
System.out.println(check); //debugging line
check += 1;
card = (int)Math.ceil(Math.random() * 13) + " ";
card_val = (int)Math.ceil(Math.random() * 13);
isIn = true;
in = 0;
break;
}
}
}
if(isIn){
//will execute if there is 4 of the cards already drawn so the while loop continues with a different card
checking = true;
}
else{
//breaks out of while loop because the card can be drawn
checking = false;
}
}
used += card;
Run Code Online (Sandbox Code Playgroud)
现在这个运行,但是当我把它放在for循环中并将其设置为运行40次时,大约2/3次它会创建一个无限循环.
我发现只有在if(in == 4)语句出现时才会创建无限循环.
为什么是这样?自昨晚以来我一直在调试,我无法弄清楚这一点.
一旦您设置isIn到true,你从来没有回false.因此,if在底部声明将保持设置checking到true,导致一个无限循环.
设置isIn为循环false的开头while.
while(checking){
isIn = false; // Add this line.
for(int q = 0; q < used2.length; q++){
Run Code Online (Sandbox Code Playgroud)