How Should I Deal with the Ace in my Java Blackjack game? Also, how can I stop duplicate card dealings?

I'm writing a blackjack game that so far, does what it should except for dealing with when and how to count ace as 1 or 11. I have two methods I've tried. They are:

  public static int calcScore(ArrayList<Card> hand){
    int sum = 0;
    for (Card c : hand){
        sum += c.getCardValue().getNumeric();
      }    
    return sum;
  }

and

  public static int calcScore(ArrayList<Card> hand){
    Scanner aceHandler = new Scanner(System.in);
    int sum = 0;
    boolean countedAce = false;

    for (Card c : hand){
      if (!c.getCardValue().getFace().equals("A")){
      sum += c.getCardValue().getNumeric();
      }
      else{
        if (sum >= 11){
          sum += 1;
        }

        else if (countedAce == false){
          System.out.println("Do you want 1 or 10 for ace? \n Enter '1' or '11'");
          String answer = aceHandler.nextLine();

          if(answer.equals("1")){
            sum+=1;
            countedAce = true;
          }
          else{
            sum+=11;
            countedAce = true;
          }
        }

      }
    }
    return sum;
  } 

the top one can't do anything with the Ace, and the bottom one kept asking for input after putting in "1" or "11". I'm running the ultimate game in the main(String[] args). How can I get either of these methods to go?

Also, I'm having an issue with sometimes, my dealIn(ArrayList hand) method deals in duplicates. I tried to design it to avoid it:

  public static ArrayList<Card> dealIn(ArrayList<Card> hand){

    Card a = new Card();
    Card b = new Card();

    hand.add( a);

    if(!b.equals(a))
      hand.add(b);

    return hand;
  }

that (!b.equals(a)) clause was supposed to avoid them, but it sometimes doesn't. How can I fix that?

1 answer

  • answered 2017-06-17 18:57 alzee

    What you want to do is ignore the aces until you've counted everything else in the hand, then count the aces, counting each one as 11 if the hand is 10 or less, or 1 otherwise. I can javaize this if you need me to, but I think the pseudocode should be enough:

    sum = 0;
    aces = 0;
    for each (card in hand) as card
    {
      if card is ace
        aces++
      else
        sum += card.value
    }
    
    while aces > 0
    {
      aces--
      if sum <= 10
        sum += 11
      else
        sum += 1
    }