首页 > 解决方案 > 如何在我的二十一点破产系统中修复此 if 语句?

问题描述

我是编码和学校作业的新手。我正在用 Java 编写二十一点。这可能是一个简单的修复,但我的代码做到了


经销商总数为7

你的总数是 11

你想要另一张卡吗?是/否


你的总数是 20 你想要另一张卡吗?是/否


你的总数是 26 你想要另一张卡吗?是/否


你的总数是 26 你破产了 你现在有 $400.0 你想再玩一次吗?是/否

.

问题是它高于 21,但直到下一个循环才告诉你你破产了。我希望它只说最后一个,而不是倒数第二个和最后一个。

System.out.println("would you like another card? \ny/n");
answer = sanswer.nextLine();

//if player answers
while ("y".equals(answer)) {
    if (total < 21){
        hit = (int) Math.floor(Math. random() * 10) + 1;
        total += hit;
        System.out.println("____________________________\n");
        System.out.println("Your total is " + total);
        System.out.println("Would you like another card? \ny/n");
        answer = sanswer.nextLine();
    }  
    //player bust
    if (total > 21) {
        System.out.println("______________");
        System.out.println("Your total is " + total);
        System.out.println("You went bust");     
        System.out.println("You now have $" + money);
        play = "no";
        System.out.println("Would you like to play again? y/n");
        answer = "";
        play = srplay.next();
    }
}

标签: javaloopsif-statementwhile-loopblackjack

解决方案


考虑这个地方:

total += hit;

此时总数可能超过 21。检查此。基于价值行动:

if (total > 21) { /* do something here */ }

推荐阅读