printing in methods vs printing in the main/driver class

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++)

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?

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.


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *