javablackjackgambling

BlackJack Program, string value issue


I'm in the midst of creating a BlackJack program. I'm currently in the "number checking" process. So once the cards have been dealt and the player asks for a "Hit" I need to check if the cards they have exceed, 21. I tried this :

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

But it soon came to my realization that because my card array is an array of strings, I cannot use mathematical operators to check wether or not the cards exceed 21. I was wondering if there was anyway to assign a Int value to each of my strings so that I can check mathematically wether or not they exceed 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()));
  }
}

I'd appreciate any suggestions/advice.


Solution

  • As JacobIRR said in his comment you can use Map but I would recommend you to use the key as a String (The card name) and the value as Integer (the value of the card).

    Remember you can not give Map int as a Key, it has to be Integer (You cannot use primitive types in Map)

    It will be like this:

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

    and put all your cards like this:

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

    Then your if condition will be like this:

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