0

所以我正在编写一个程序,其中有人从一副牌中抽牌。所以我写了一个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)

为什么是这样?我从昨晚开始一直在调试,我无法弄清楚。

4

2 回答 2

6

一旦设置isIntrue,就永远不会将其设置回false。因此,if底部的语句将继续设置checkingtrue,从而导致无限循环。

在循环开始时设置isIn为。falsewhile

while(checking){
    isIn = false;  // Add this line.
    for(int q = 0; q < used2.length; q++){
于 2013-09-23T20:23:44.953 回答
0

似乎是针对简单任务的复杂算法。

为什么不改变实现以使用简单的减法?最初分配List所有 52 个值中的一个,然后当您从牌组中“抽出”牌时,将其从列表中删除。

那么你可以用它Math.random() * list.size()来获得一个适当范围的索引吗?

于 2013-09-23T20:27:51.550 回答