【发布时间】:2013-09-28 20:55:33
【问题描述】:
所以我正在编写一个程序,其中有人从一副牌中抽牌。所以我写了一个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) 声明为真时才会创建无限循环。
这是为什么?从昨晚开始我一直在调试,我无法弄清楚。
【问题讨论】:
-
写
if-else声明的更简洁的方式:checking = isIn; -
因为您在该块中将
isIn设置为true,这意味着checking永远不会设置为false。 -
对
(int)Math.ceil(Math.random() * 13) + " "的评论。我怀疑您使用" "的原因是将int 转换为String,但是您只能执行+"",这会使之后的代码更简单.. -
@KubaSpatny:我不确定你的意思是什么
-
@RyanSaxe 那么
+" "的原因是什么?
标签: java for-loop while-loop infinite-loop