Hello!

I am very new to Java and programming theory and desperately trying to improve my knowledge. This is the first program I've made without help and really would appreciate some feedback. I know there must be 1,000,000 better ways to do what I did.

Notes:

  • Want to Move Into OOP
  • I am aware that the Ace should not just be = 11 and give the user the chance to dictate it's value but implementing that would not of taught me anything new.

Really want to nail this BlackJack method and make it as effecient, OOP and true to programming models as possible

Code:

/*
 * Imports
 */
import java.util.*;

public class BlackJackGame {

    /*
     * Array list to store users and dealers cards
     */
    public ArrayList<String> usersCards = new ArrayList<String>();
    public ArrayList<String> dealersCards = new ArrayList<String>();

    /*
     * Array for storing potential cards
     */
    String[] card = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
            "Jack", "Queen", "King", "Ace"};
    /*
     * Dealer && User Variables
     */
    int usersValue = 0;
    int dealersValue = 0;
    int usersDecision = 0;

    boolean userTwisting = false;
    boolean dealerTwisting = false;
    boolean dealerNotBust = true;


    /*
     * Scanner
     */
    Scanner kb = new Scanner(System.in);

    BlackJackGame() {

        /*
         * Start Game
         */

        /*
         * Generate Dealer && Users Cards
         * First Portion Of Game
         */
        generateDealersCard();
        generateUsersCard();
        generateUsersCard();
        displayUsersCards();
        displayDealersCards();
        checkBlackJack();

        /*
         * Second Portion Of Game
         */
        userOptions();

        usersDecision = kb.nextInt();
        do {
            if(usersDecision == 1) {
                generateUsersCard();
                displayUsersCards();
                checkBlackJack();
                checkBust();

                userOptions();
                usersDecision = kb.nextInt();
            } else {
                userTwisting = false;
            }
        }while(userTwisting == true);

        do {
            getDealersValue(dealersValue);
            checkDealersActions();
        } while (dealerNotBust = true);

    }
    /*
     * Dealers Cards Value
     */
    public int getDealersValue(int dValue) {
        dValue = 0;

        for(int i = 0; i < dealersCards.size(); i++) {
            if(dealersCards.get(i).equals("2")) {
                dValue += 2;
            } else if(dealersCards.get(i).equals("3")) {
                dValue += 3;
            } else if(dealersCards.get(i).equals("4")) {
                dValue += 4;
            } else if(dealersCards.get(i).equals("5")) {
                dValue += 5;
            } else if(dealersCards.get(i).equals("6")) {
                dValue += 6;
            } else if(dealersCards.get(i).equals("7")) {
                dValue += 7;
            } else if(dealersCards.get(i).equals("8")) {
                dValue += 8;
            } else if(dealersCards.get(i).equals("9")) {
                dValue += 9;
            } else if(dealersCards.get(i).equals("10")) {
                dValue += 10;
            } else if(dealersCards.get(i).equals("Jack")) {
                dValue += 10;
            } else if(dealersCards.get(i).equals("Queen")) {
                dValue += 10;
            } else if(dealersCards.get(i).equals("King")) {
                dValue += 10;
            } else if(dealersCards.get(i).equals("Ace")) {
                dValue += 11;
            }
        }
        dealersValue = dValue;
        return dValue;
    }
    /*
     * Generate Dealers Cards
     */
    void generateDealersCard() {
        int randomGenNumber = (int) (Math.random()*13);

        dealersCards.add(card[randomGenNumber]);
    }

    /*
     * Users Cards Value
     */
    public int getUsersValue(int uValue) {
        uValue = 0;

        for(int i = 0; i < usersCards.size(); i++) {
            if(usersCards.get(i).equals("2")) {
                uValue += 2;
            } else if(usersCards.get(i).equals("3")) {
                uValue += 3;
            } else if(usersCards.get(i).equals("4")) {
                uValue += 4;
            } else if(usersCards.get(i).equals("5")) {
                uValue += 5;
            } else if(usersCards.get(i).equals("6")) {
                uValue += 6;
            } else if(usersCards.get(i).equals("7")) {
                uValue += 7;
            } else if(usersCards.get(i).equals("8")) {
                uValue += 8;
            } else if(usersCards.get(i).equals("9")) {
                uValue += 9;
            } else if(usersCards.get(i).equals("10")) {
                uValue += 10;
            } else if(usersCards.get(i).equals("Jack")) {
                uValue += 10;
            } else if(usersCards.get(i).equals("Queen")) {
                uValue += 10;
            } else if(usersCards.get(i).equals("King")) {
                uValue += 10;
            } else if(usersCards.get(i).equals("Ace")) {
                uValue += 11;
            }
        }
        usersValue = uValue;
        return uValue;

    }
    /*
     * Generate Users Cards
     */
    void generateUsersCard() {
        int randomGenNumber = (int) (Math.random()*13);

        usersCards.add(card[randomGenNumber]);

        userTwisting = true;
    }
    /*
     * Display Users && Dealers Cards
     */
    public void displayUsersCards() {
        System.out.println("You Have: " + usersCards);
    }
    public void displayDealersCards() {
        System.out.println("The Dealer Has: " + dealersCards);
    }
    /*
     * Check For BlackJack
     */
    public void checkBlackJack() {

        getDealersValue(dealersValue);
        getUsersValue(usersValue);
        /*
         * Check Dealers BlackJack
         */
        if(dealersValue == 21) {
            System.out.println("Dealer Has BlackJack! You Lose");
            System.exit(0);
        }
        if(usersValue == 21) {
            System.out.println("You Have BlackJack! You Win!");
            System.exit(0);
        }

    }
    /*
     * Compare Values
     */
    public void compareValues() {
        getDealersValue(dealersValue);
        getUsersValue(usersValue);

        if(dealersValue == usersValue) {
            System.out.println("\nDealers Value: " + dealersValue
                    + " Users Value: " + usersValue);
            System.out.println("You've Drawn!");
            System.exit(0);
        }
        if(dealersValue > usersValue) {
            System.out.println("\nDealers Value: " + dealersValue
                    + " Users Value: " + usersValue);
            System.out.println("You've Lost!");
            System.exit(0);
        } else {
            System.out.println("\nDealers Value: " + dealersValue
                    + " Users Value: " + usersValue);
            System.out.println("You Won!");
            System.exit(0);
        }


    }
    /*
     * Check For Bust
     */
    public void checkBust() {

        getDealersValue(dealersValue);
        getUsersValue(usersValue);

        if(dealersValue > 21) {
            System.out.println("Dealer Has Bust - You Win!");
            System.exit(0);
        }

        if(usersValue > 21) { 
            System.out.println("You've Bust - You Lose!");
            System.exit(0);
        }
    }

    /*
     * Check Dealers Actions
     */
    public void checkDealersActions() {

        getDealersValue(dealersValue);

        if(dealersValue <=16) {
            System.out.println("Dealer Has 16 or Less - Twisting");
            generateDealersCard();
            displayDealersCards();
            checkBust();
            checkBlackJack();
        }

        if(dealersValue == 17) {
            System.out.println("Dealer Has 17 - Sticking");
            compareValues();
        }

        if(dealersValue > 17) {
            System.out.println("Dealer Has: " + getDealersValue(dealersValue) + " - Sticking");
            compareValues();
            System.exit(0);
        }

    }

    public void userOptions() {
        System.out.println("Do You Want To:\n [1] Twist\n [2] Stick");
    }

    public static void main(String[] args) {

        new BlackJackGame();


    }
}

Thank you for your time.

Recommended Answers

All 33 Replies

That's good progress - you learn fast!
Let's get rid of the duplicated code for getting the value of a card... maybe a method that has all the "if card equals... value = ..." lines
public static int getCardValue(String card) { ...
then you can simplify code like this

for(int i = 0; i < dealersCards.size(); i++) {
    dValue += getCardValue(dealersCards.get(i));
}

Thanks! You helped SO much in the other thread!

OK, this is what I have so far...

int cardValue = 0;


public int getCardValue(String card, int cValue ) {

        if(card == "2") {
            cValue += 2;
        }
        if(card == "3") {
            cValue +=3;
        }   
        return cValue;
        cardValue = cValue;

    }

Is this at all right? Struggling to grasp it!

if(card == "2") {

Use the equals() method to compare Strings.

The compiler should tell you there is an unreachable statement (after return)

Fixed that, thank you! I haven't worked with Strings like this for a while >.<

On the card values, I would recommend using a HashMap as a reverse lookup table for the card face values. Something like this should do:

private HashMap<String, int> faceValues = new HashMap<String, int>(20);

faceValues.put("Ace", 1);
faceValues.put.("Deuce", 2);
faceValues.put("Trey", 3);
// handle all the numbered cards
for (int i = 4; i <= 10; i++) {
    faceValues.put(Int.toString(i), i);
}
faceValues.put("Jack", 10);
faceValues.put("Queen", 10);
faceValues.put(King", 10);

You'll need some additional logic for handling the case where Ace is treated as 11, but beyond that, this should make looking up the card values much easier.

 /*
  * Dealers Cards Value
  */
 public int getDealersValue(int dValue) {
     dValue = 0;
     for(int i = 0; i < dealersCards.size(); i++) {
         String card = dealersCards.get(i);
         if (card == "Ace") {
             if (dValue <= 10) {
                 dValue += 11;
             }
             else {
                 dValue += 1;
             }
         }
         else {
             dValue += faceValues.get();
         }   
     }

     dealersValue = dValue;
     return dValue;
 }

The same would be done with the user's cards, except that the user would have to be queried abuot how to treat the aces.

Would you mind going into detailing or providing solid literature on HashMaps? I have never heard of them before, why are they superior?

Reading your code it makes sense, just curious as to when HashMaps are the way to go? What can they provide that an ArrayList etc can't? Thanks!

Also, would it be possible for someone to outline how I achieve the most amount of OOP for BlackJack please? I would really like to finally get to grips with OOP.

Also, would it be possible for someone to outline how I achieve the most amount of OOP for BlackJack please? I would really like to finally get to grips with OOP.

There are some pointers in my last full post to your previous thread...
J

Player user1 = new Player();
Dealer dealer = new Dealer();
Deck deck = new Deck();
deck.shuffle();
user1.takeCards(deck.deal(2));
if (user1.twists()) then ...

What would my classes and methods skeleton look like in this case?

Oh, sorry; I should have provided more information. The Java HashMap generic class is a standard Collection that behaves as a dictionary or lookup table (sometimes also called an associative array or associative map). It provides a mapping between two values.

When you create the HashMap, you give it two types, one for the key and the other for the value. You add key-value pairs to the HashMap to make the table. You can then use a key to look up a value in the HashMap.

As for why they are superior to an ArrayList, they aren't; they are used in a completely different way from an ArrayList with very little overlap. What they are superior to in this case is the long sequence of if() statements which you were using to determine the values for the cards. Not only is it more compact, you can use it in mutiple locations with very little code. It is an approach known as data-directed programming, where you use the structure of the objects to provide the solution to a problem rather than relying on code for it.

Oh, I noticed a few errors in my earlier code; notably, I used == where I should have used .equals(), and forgot to pass card to the .get() method of the HashMap.

     if (card.equals("Ace")) {
          if (dValue <= 10) {
              dValue += 11;
          }
          else {
              dValue += 1;
          }
      }
      else {
          dValue += faceValues.get(card);
      }

HTH.

That's great information, thanks Schol-R-LEA! Will definately have to think about how I approach programs now that I have HashMaps in my arsenal!

Going to implement your HashMap technique into my current code.

Does anyone have anything to chip into my third and final attempt at BlackJack where I will try to attempt complete (or as close to as a beginner can) OOP coding? Would be greatly appreciated! Want to capitalise on my few days off! :-)

What would my classes and methods skeleton look like in this case?

You have class names and some method calls there - so that's your starting point. Just define the classes, add some (private) variables for the obvious data, accessor methods as required for the data, constructor(s), other methods as mentioned...
You'll find that once you get started it will fall into place.
ps: HashMap is a good way to improve your V2 code, but with the OO version it's not needed because the value of a Card is an instance variable of the Card class and each instance has it's own value.

OK, thank you so far I have:

public class BlackJack{

}

public class Card {

}

public class Players {

}

public class Deck {

}

So,

I need to create 52 objects of card in Deck. Then when a Player ( dealer = new Player, user = new Player, need a new card I can just retrieve one from the deck object.

Am I at all on the right lines? Struggling to grasp this concept, sorry!

Yes. Exactly that. The constructor for Deck will need to create 52 new Cards and add them to a list of some sort. Then it can have a public method that gets a random card from that list and returns it to whoever asked for it. Obviously you'll need a constructor and a variable or two for the Card class before you can get too far with Deck.
Try filling in a few of the variables that you think each class will need.

import java.util.Random;

public class Card extends BlackJack {

    private int randomNum;

    String[] value = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
                        "Jack", "Queen", "King", "Ace"};
    String[] suit = {"Hearts", "Clubs", "Spades", "Diamonds"};

    private String valueCard;
    private String suitCard;

    public Card(String v, String s) {

        valueCard = v;
        suitCard = s;

    }

    public void generateValue(String v) {
        randomNum = (int) (Math.random()*13);
        v = value[randomNum];
    }
    public void generateSuit(String s) {
        randomNum = (int) (Math.random()*3);
        s = suit[randomNum];
    }


    public String getValue() {
        return valueCard;
    }
    public String getSuit() {
        return suitCard;
    }

    public void setValue(String v) {
        valueCard = v;
    }
    public void setSuit(String s) {
        suitCard = s;
    }
}

Any luck with this? Still struggling to wrap my head around it!

If the above code is along the right lines.

To create a deck of 52 cards, would I do a for loop 52 times creating a new object of Card?

So roughly:

public class Deck {

    deck[52][52]

    for loop 52 times {
     for loop 52 times {
       generate value
       generate suit



    takeFromDeck() {
    randomNum;
    randomNum2;

    cardTaken = deck[randomNum][randomNum2];

    }

When I try to create an object of Card in Deck using:

Card card = new Card();

it throws back:

Card card = new Card(null, null);

Do I have too make two private String variables in the deck class to pass through?

Thanks.

Card doesn't extend BlackJack - it's not a kind of BlackJack
You don't want the set methods - you can't change a Card's suit or value.
I don't think you need the random methods either?
Your constructor needs to Strings for value and suit, so you need to pass those strings when you call it, so to create a full deck it's something like:

for each suit (the list of suits needs to be in Deck for this
    for each value (ditto the list of values
         new Card(value, suit)

then you add each card to the deck's internal list of cards (you;ll find it easier to use an ArrayList than an array). A deck is a single-dimensional kind of thing, not 2d. (When in doubt, think about the real-life object that your code is modelling - what does a deck of cards really look like?).
takeFromDeck needs to return the Card it took so the user/dealer knows what Card they got. All you need to do is to remove one random card from the Deck's list of crads.

You don't necessarily want to hard-code the size of the Deck, either. The reasons for this are four-fold:

  • As the play goes on, the size of the Deck will decrease, until it reaches the point where you need to reshuffle the discards, at which point it will go back to the original size,
  • You may want to extend your deck with additional Cards (e.g., jokers),
  • You may want a 'shoe' of cards consisting of more than one 52-card deck (as is done in most casinos), and
  • The easiest way to handle the player's hand is to sub-class Deck, in which case the size will always be smaller than 52.

Just some advice based on my own experience implementing a card game.

Thanks for the tips Schol-R-LEA! Taken on board.

I editted my code:

public class Card{



    private String valueCard;
    private String suitCard;

    public Card(String v, String s) {
        valueCard = v;
        suitCard = s;
    }

    public String getValue() {
        return valueCard;
    }
    public String getSuit() {
        return suitCard;
    }

}



import java.util.ArrayList;


public class Deck {

    ArrayList<String> deck = new ArrayList<String>();

    String[] value = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
            "Jack", "Queen", "King", "Ace"};
    String[] suit = {"Hearts", "Clubs", "Spades", "Diamonds"};



    public void createDeck(String v, String s) {
        for(int i = 0; i < suit.length; i++) {
            for (int x = 0; x < value.length; x++) {
                new Card(v, s);
            }
        }

    }
}

The annoying thing is, I am looking at my card and I KNOW it doesn't do anything (for example it does not add the card to the ArrayList), and even if I did add it to the ArrayList, it's going to be null, isn't it?

This is frustrating haha, I know what needs to be done but my brain just can't process how I get there!

Thanks for all your help so far, appreciate it! Hopefully soon I'll get to grips with OOP!

deck should be a list of Cards, not Strings.
When you create a new Card you add it to that list (line 40)
So your deck constructor (not a createDeck method - that's what a constructor does!) needs no parameters - it just loops thru all the suits and values creating the 52 cards and adding them to the list.

ps This being BalckJack then each card also has a numeric value 1- 10

The deck instance variable probably should be an ArrayList<Card> rather than ArrayList<String>.

I would make the suits and values of the card enumeration types, rather than strings; that way, you can change the representation (using abbreviations, for example, or images of some kind), without needing to change the Card or Deck classes themselves. This sort of decoupling of the user interface with the logic is often a valuable approach.

enum Suit {Hearts, Clubs, Diamonds, Spades};

enum Face {Ace, Deuce, Trey, Four, Five, 
           Six, Seven, Eight, Nine, Ten,
           Jack, Queen, King};

public class Card {

    private Suit suit;
    private Face value;

    public Card(Face v, Suit s) {
        value = v;
        suit = s;
    }

    public String getValue() {
        return value;
    }

    public String getSuit() {
     return suit;
    }
}

Fortunately, Java enumerations are a lot more flexible than those in C or C++, and you can extract the string form of an enumerated value just by using either name() or ToString(). Thus, while you can decouple the interface if you choose, you can also 'cheat' a bit and use the actual enumerated values.

You probably want to write one or more comparison methods for the Card class.

OK so I have:

import java.util.ArrayList;


public class Deck {

    ArrayList<Card> deckList = new ArrayList<Card>();

    String[] value = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
            "Jack", "Queen", "King", "Ace"};
    String[] suit = {"Hearts", "Clubs", "Spades", "Diamonds"};


    Deck() {


    }

public void createDeck(String v, String s) {
    for(int i = 0; i < suit.length; i++) {
        for (int x = 0; x < value.length; x++) {
            deckList.add(new Card(v, s));
        }
    }
}
}

But here is where I think I've bitten off a little more than I can chew:

  1. How do I call createDeck in the Deck() method? If I do :
    createDeck()
    it starts asking me for parameters, so I put my for loops into the Deck() method, again asking for parameters.
  2. Pseudo code:

    //Deck needs to be formed
    public void createDeck(String v, String s)
    loop suit length
    loop value length
    add new card to deckList

    Deck()
    for loop 52 times
    call createDeck
    

So I need to create an OBJECT of 1 card.
Then create an object of DECK and fill it with 52 objects of card?

I really am struggling to grasp this concept! Thanks a lot for your patience so far.

Edit: Just read your post, thank you I will change to enums and do a bit of research on them.

Hey fellas, I stayed away as long as I could but I've hit a problem I cannot wrap my head around!

My issue: How do I derive my values from my enums? I can't for the life of me figure it out! I've googled around and a lot of results came back with:

Deuce(2) or Deuce("2") but even then I could not get it down!

I am trying to calculate the "value" of the users and dealers hands that are stored in my ArrayLists.

This is what my code currently outputs:

The Dealer Has: [Six of Clubs]
You Have: [Queen of Clubs, Ace of Spades]

Now, I want to retrieve from this information:

dealerValue = 6
userValue = 21

I've made a fair bit of progress! All the code is new:

public class BlackJack{

    BlackJack() {       
        /*
         * Create New Deck

         */
        Deck deck =  new Deck();


        /*
         * Fill Deck With 52 Cards
         */
        deck.createDeck();

        /*
         * Randomise 52 Cards
         */
        deck.shuffle();

        /*
         * Initial Gameplay
         */
        deck.addCardUser();
        deck.addCardUser();

        deck.addCardDealer();

        /*
         * Print Initial Cards
         */

        System.out.println("The Dealer Has: " + deck.dealer.getDealerList());
        System.out.println("You Have: " + deck.user.getUserList());

    }

    public static void main(String[] args) {

        new BlackJack();


    }
}




import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class Deck {

    ArrayList<Card> deckList = new ArrayList<Card>();



    Player user = new Player();
    Player dealer = new Player();

    /*
     * Constructor
     */
    Deck() {

        deckList = new ArrayList<Card>();
    }

    /*
     * Create Un-Shuffled Deck
     */
    public void createDeck() {

        for (Suit suit : Suit.values()) {
            for (Rank rank : Rank.values()) {   
                deckList.add(new Card(rank, suit)); 

            }
        }
    }

    /*
     * Shuffle
     */
    public void shuffle() {
        Collections.shuffle(deckList);
    }

    /*
     * Add Card User && Dealer
     */
    public void addCardUser() {
        user.userList.add(deckList.get(0));
        deckList.remove(0);
    }
    public void addCardDealer() {
        dealer.dealerList.add(deckList.get(0));
        deckList.remove(0);
    }

}




import java.util.ArrayList;


public class Player {

    /*
     * ArrayLists To Hold Cards
     */
    public ArrayList<Card> userList = new ArrayList<Card>();
    public ArrayList<Card> dealerList = new ArrayList<Card>();

    /*
     * Private Variables
     */

    public int userValue;
    public int dealerValue;

    /*
     * Constructor
     */
    Player() {

    }

    public ArrayList<Card> getUserList() {
        return userList;
    }

    public ArrayList<Card> getDealerList() {
        return dealerList;
    }

}




public class Card{

    //private Rank rank;
    private Suit suit;
    private Rank rank;



    public Card(Rank rank, Suit suit) {
        //this.rank = rank;
        this.suit = suit;
        this.rank = rank;
    }

    public Suit getSuit() {
        return suit;
    }

    public Rank getRank() {
        return rank;
    }

    @Override
    public String toString(){
        return rank +  " of "  + suit;
    }
}



public enum Suit {
        Clubs, Diamonds, Hearts, Spades
    }




public enum Rank {  
        Deuce, Three, Four, 
        Five, Six, Seven, 
        Eight, Nine, Ten,
        Jack, Queen, King, 
        Ace;    
}

Thank you very much for your time and help.

Forget createDeck - it's unneccessary and confusing. Just have a construtor for Deck that fills its list with 52 new Cards.

An enum is like an ordinary class, in that you can have variables, methods, and a constructor within their definition. The enum values {Deuce, Three etc) can have parameter, and these are passed to the constructor.

 public enum Rank {Deuce(2) ...
     private int value;
     Rank(int value) {  // constructor 
         this.value = value;
     }
     public int getValue() {
        return value;
     }
     ...

As it happens, there is a class named EnumMap which is designed for precisely this situation. It provides a mapping keyed to an enumeration. I this case, you would use it something like this in the class BlackJack:

static final EnumMap<Rank, int> rank_value = new EnumMap<Rank, int>(Rank);

static {
    rank_value.put(Rank.Deuce, 2);
    rank_value.put(Rank.Three, 3);
    rank_value.put(Rank.Four, 4);
    rank_value.put(Rank.Five, 5);
    rank_value.put(Rank.Six, 6);
    rank_value.put(Rank.Seven, 7);
    rank_value.put(Rank.Eight, 8);
    rank_value.put(Rank.Nine, 9);
    rank_value.put(Rank.Ten, 10);
    rank_value.put(Rank.Jack, 10);
    rank_value.put(Rank.Queen, 10);
    rank_value.put(Rank.King, 10);
    rank_value.put(Rank.Ace, 11);
};

You could then use this to get the values of the cards:

    /*
    * Print Initial Cards
    */
    System.out.print("The Dealer Has: " + deck.dealer.getDealerList() + " for a total of ");
    int dv = 0;
    for (Card card : deck.dealer.getDealerList()) {
        dv += rank_value.get(card.getRank());
    }
    System.out.println(dv);

    System.out.print("You Have: " + deck.user.getUserList()  + " for a total of ");
    int pv = 0;
    for (Card card : deck.user.getUserList()) {
        pv += rank_value.get(card.getRank());
    }
    System.out.println(pv); 

I hope it is clear how this works.

Hi Schol-R-LEA
What you say is true, but, in this context, how would you describe the advantages of using an extra data structure and code like this, rather than just adding an attribute to the enum itself?

commented: Thanks! +0

Mainly, that it leverages the existing EnumMap class rather than having to write a c'tor and accessors for the Rank class. Also, because it decouples the value of the cards from the Rank class, it makes easier to re-use the classes for another type of card game (e.g., poker, bridge). While neither of these is a big deal in this particular case, they are good design practices to get familiar with.

commented: Thanks! +2

Hey, thanks for the replies!

I tried Schol-R-LEA's method and I get the error:

static final EnumMap<Rank, int> rank_value = new EnumMap<Rank, int>(Rank);

So I attempted JamesCherrill's method:

public enum Rank {  
    Deuce(2), Three(3), Four(4), 
    Five(5), Six(6), Seven(7), 
    Eight(8), Nine(9), Ten(10),
    Jack(10), Queen(10), King(10), 
    Ace(11);    


    private int value;

    Rank(int value) {
        this.value = value;
    }

    public int getValue( int value) {
        return value;
    }
}

I've tried implementing it to retrieve the value, alas my knowledge lets me down yet again.

Cannot wait to have this project completed so I can go back to scratch and re-learn OOP from the ground up!

Any tips on how to get it to check users/dealers cards, take what is in the array list and retrieve their card values?

Thanks.

Using the approach I preferred (for this particular application, EnumMap will be better for some other applications) you can get the value from a Card by just calling its getValue() method

Card c1 = ... something 
int theValue = c1.getValue();

BUT NB your getValue method is wrong - it does not need or take a parameter. it should be as in my previous post:

public int getValue() {
   return value;
}
commented: Thanks! +2

Hey James, thanks for your reply!

Gutted about trying to pass an int through my old getValue() method, my attempts would have worked otherwise!

I added this to my Deck.java:

public int getUserValue() {
        userValue = 0;

        for(int i = 0; i < user.getUserList().size(); i++) {
            userValue +=  user.getUserList().get(i).getRank().getValue();
        }
        return userValue;
    }

and to BlackJack.java:

System.out.println("User Value: " + deck.getUserValue());

so far so good! :D

Thanks a lot for your help guys, really appreciate it!

Hey guys,

Everything is going really well but I cannot get my Ace 1 or 11 from user input concept nailed.

So:

Check List If Ace Exists
If Ace Found

Prompt User: Ace Value 1 or 11?
if 1: uValue += 1
if 11: uValue += 11

That's fine, but I re-calculate their value everytime, how do I store that they've opted for the ace to equal 1 or 11? How do you deal with multiple aces?

The re-evaulation of the value is really throwing me off, unless there is a way to only add the latest added card.

Maybe something along these lines?

int currentUValue;
int currentCard;
generateTwoCards
currentCard = 1;
if user twists currentCard++

When twisted, uValue += user.getUserList.get(currentCard).getRank().getValue();

Seems like a reasonable solution, would this be OK? Would you make any alterations?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.