0

我正在创建一个 BlackJack 程序。我目前处于“号码检查”过程中。因此,一旦发牌并且玩家要求“击中”,我需要检查他们所拥有的牌是否超过 21。我试过这个:

if(pCard1+pCard2+pCard3 > 21)
    System.out.println("Bust!"); 

但很快我就意识到,因为我的卡片数组是一个字符串数组,我不能使用数学运算符来检查卡片是否超过 21。我想知道是否有任何方法可以为我的每个字符串分配一个 Int 值这样我就可以在数学上检查它们是否超过 21。

    else if(game == 3) {
 int bet = 0;
 String HoS;
 ArrayList<String> cards = new ArrayList<String>();
 cards.add("1");
 cards.add("2");
 cards.add("3");
 cards.add("4");
 cards.add("5");
 cards.add("6");
 cards.add("7");
 cards.add("8");
 cards.add("9");
 cards.add("10");
 cards.add("Jack");
 cards.add("Queen");
 cards.add("King");
 cards.add("Ace");

 System.out.println("------------------BLACKJACK---------------------");
 System.out.println("Welcome to BlackJack!");
 System.out.println("Current balance $"+balance);
 System.out.print("How much would you like to bet on this hand?:");
    bet = input.nextInt();
 System.out.println("--------------------------------------------------------------------");
 System.out.println("Dealing cards.........");

 Random card = new Random();
 String pCard1 = cards.get(card.nextInt(cards.size()));
 String pCard2 = cards.get(card.nextInt(cards.size()));

 System.out.println("Your hand is a "+pCard1+","+pCard2);
 System.out.print("Would you like hit or stand?:");
    HoS = input.next();
if(HoS.equals("Hit")) {
    String pCard3 = cards.get(card.nextInt(cards.size()));
        System.out.print("*Dealer Hits* The card is "+pCard3);
    }
else if(HoS.equals("Stand")) {
    System.out.println("Dealing Dealer's hand........");
    String dCard1 = cards.get(card.nextInt(cards.size()));
    String dCard2 = cards.get(card.nextInt(cards.size()));
  }
}

我很感激任何建议/建议。

4

2 回答 2

1

你可以做 :

import java.util.Map;
import java.util.HashMap;
Map<Int, String> dictionary = new HashMap<Int, String>();

然后添加每个项目:

dictionary.put(1, "Ace");
于 2018-03-31T19:30:59.140 回答
0

正如 JacobIRR 在他的评论中所说,您可以使用Map,但我建议您将密钥用作String(卡名),将值用作Integer(卡的值)。

请记住,您不能Map int作为键给出,它必须是Integer(您不能在中使用原始类型Map

它会是这样的:

Map<String, Integer> cards = new HashMap<String, Integer>(); 

把你所有的卡片都像这样:

cards.put("1", 1);
cards.put("2", 2);
...
cards.put("Jack", 11);
cards.put("Queen", 12);
cards.put("King", 13);
cards.put("Ace", 1);

那么你的if condition会是这样的:

if(cards.get(pCard1) + cards.get(pCard2) +cards.get(pCard3) > 21)
    System.out.println("Bust!"); 
于 2018-03-31T19:31:01.527 回答