2

I'm fairly new to programming and am currently creating a blackjack game in Java.

I've progressed quite well, although could use some pointers with regards to the best way to implement a method.

At various points during a game of blackjack it's important to show the user what cards are in their hand. I have a PlayerHand class and a method that returns a card at index i as a string.

public String displayCard (int i)
{
    return hand.get(i).getCard();
}

'hand' is an ArrayList representing the hand and the .getCard() method on the card is as follows...

public String getCard ()
{
    return "The "+mCardValueName+" of "+mCardSuit;
}

This all seems well and good for returning the card at index i in a players hand, however what should I do if I want to display the entire hand?

I was thinking to do something like the following....

public void displayHand ()
{
    for (int i = 0; i < hand.size(); i++)
    {
        System.out.println(displayCard(i));
    }
}

So calling the displayCard() method within the displayHand() method in a loop and printing.

Is this good programming practice to loop and print in a method? I don't want to write for loops in the main class each time I want to display the players cards in hand. Also, is there a way to easily return multiple Strings from a method?

3

This is good programming practice, because you are separating the functionality of printing the retrieved card from actually retrieving the card from the deck /object.

It's fine that you have a for loop that prints everything, it doesn't matter whether it's in the main or in the displayHand. What you would not want to do is print inside of the getHand, because that would mix the functionality of your methods and might make your program unclear or difficult to use.

Additionally, you can return multiple Strings from your method without a problem. Consider returning an array of Strings (multiple Strings). The function stub would be:

public String[] getCards()
{
    // code
}

Note: It's always good to separate the user/operator interface from the API classes being utilized in your application.

  • 1
    Thanks StevieV. Ah yes forgot I could just return an array of strings. Would I be correct in thinking my solution might still be preferable in this scenario as even if I return all the cards in a string array in a method, I would still need to write a loop each time I want to display them all in my main class? – Konzy262 Mar 9 '16 at 12:24
  • Right, you would still need some kind of a loop to parse each element of the array. You could do this nicely with a "foreach" loop if you wanted to, or as you said a "for" loop. – Snoop Mar 9 '16 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.