【问题标题】:java while loop not breaking outjava while循环没有爆发
【发布时间】: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


【解决方案1】:

一旦将isIn 设置为true,就再也不会将其设置回false。因此,底部的if 语句会一直将checking 设置为true,从而导致无限循环。

while 循环的开头将isIn 设置为false

while(checking){
    isIn = false;  // Add this line.
    for(int q = 0; q < used2.length; q++){

【讨论】:

    【解决方案2】:

    看起来像一个简单任务的复杂算法。

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

    那么您可以使用Math.random() * list.size() 来获取范围适当的索引吗?

    【讨论】:

    • 我还没有学过列表,这是硬件问题,我们还没有学过数组,我刚刚知道拆分方法,所以我用它来使操作字符串更容易跨度>
    猜你喜欢
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 2013-09-28
    • 2019-10-11
    相关资源
    最近更新 更多