所以我正在写一个程序,让人从一副牌中抽出纸牌。所以我写了一个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次,它创建了一个of无限循环。
我发现只有当if(in == 4)语句为真时,才会创建无限循环。
为什么会这样呢?我从昨晚开始就一直在调试,但是我搞不清楚这个问题。
发布于 2013-09-24 04:23:45
一旦将isIn设置为true,就再也不能将其设置回false。因此,底部的if语句将继续将checking设置为true,从而导致无限循环。
在while循环开始时将isIn设置为false。
while(checking){
isIn = false; // Add this line.
for(int q = 0; q < used2.length; q++){发布于 2013-09-24 04:27:52
对于一个简单的任务来说,这似乎是一个复杂的算法。
为什么不改变实现来使用简单的减法呢?最初分配一个包含全部52个值的List,然后当您从牌组中“抽出”牌时,将其从列表中删除。
那么您可以使用Math.random() * list.size()来获得一个适当范围的索引吗?
https://stackoverflow.com/questions/18968103
复制相似问题