Java中的黑杰克游戏

时间:2014-08-29 01:20:18

标签: java blackjack

问题陈述

我有另一个线索,但我似乎无法找到它。基本上,我有一个黑杰克游戏。给用户两张随机卡(然后将这些卡加在一起,并显示总数)。然后它会提示用户是否需要另一张卡(他们几乎想要总数低于21)。如果他们选择"是,"他们会得到一个随机卡号(他们可以继续获得一张卡,但应该避免超过21),但如果他们选择"不,"游戏停止了。

这是我应该得到的输出:[blackjackoutput.jpg]

以下是我得到的内容:[output1.jpg]

源代码:

public class BlackJackGame {
    public static void main(String[] args) {
        int randomnum1 = (int) (1 + Math.random() * 10);
        int randomnum2 = (int) (1 + Math.random() * 10);
        int total;
        char anotherCard = 'y';
        char playAgain;
        Scanner input = new Scanner(System.in);

        // Prints cards player starts off with
        System.out.println("First cards: " + randomnum1 + ", " + randomnum2);

        // Sum of the 2 cards
        total = randomnum1 + randomnum2;

        // Prints Total
        System.out.println("Total: " + total);

        // Do While Loop that asks question to get lower than 21 or terminate.
        while (anotherCard != 'n') {
            if (total <= 21) {
                System.out.print("Do you want another card? (y/n): ");
                anotherCard = input.next().charAt(0);

                int randomnum3 = (int) (1 + Math.random() * 10);
                System.out.println("Card: " + randomnum3);

                total += randomnum3;
                System.out.println("Total: " + total);
            } else if (total > 21) {
                System.out.println("BUST.");

                System.out.print("Would you like to play again? (y/n): ");
                playAgain = input.next().charAt(0);
            }
        } 
    }
}

问题

  1. 当我达到21岁时,我会选择&#34;不,&#34;停止该计划。但是,它会继续显示下一张卡片和更新的总数。

  2. 当我&#34;忙碌。&#34; (或者超过21)。它会问我是否想参加比赛。在不同的场合,我选择&#34; y&#34;它说&#34;胸围。&#34;并问我是否想再玩一次(它循环,说&#34; BUST。&#34;,并问我同样的问题,但不能结束该程序)。如果我选择&#34; no&#34;它会说&#34;胸围。&#34;并问我是否可以再玩一次。

  3. 你如何再次玩游戏?

  4. 请帮助!!!

1 个答案:

答案 0 :(得分:1)

你遇到的问题是一个逻辑问题:

 if (total <= 21) 
    {
      System.out.print("Do you want another card? (y/n): "); //<--------------
      anotherCard = input.next().charAt(0);

      int randomnum3 = (int) (1 + Math.random() * 10);

      System.out.println("Card: " + randomnum3);

      total += randomnum3;

      System.out.println("Total: " + total);

您需要检查if(anotherCard == 'n')以摆脱循环

旁注

这个二十一点游戏应该有一个更好的随机卡分布,更好地模仿了52张卡片

相关问题