所以我正在编写一个程序,其中有人从一副牌中抽牌。所以我写了一个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;
现在它运行了,但是当我把它放在一个 for 循环中并将它设置为运行 40 次时,大约 2/3 次它会创建一个无限循环。
我发现只有当陈述成立时才会创建无限循环if(in == 4)
。
为什么是这样?我从昨晚开始一直在调试,我无法弄清楚。