Reputation: 9
Hello I am currently trying to complete an assignment but I am having difficulty completing one of the classes, the class is called hand.cs
and it looks as follows.
The other two sources of data that hand.cs is pulling from are called card.cs
and twentyOne.cs
, before people comment I know that this is an obvious solution and might seem laughable to many of the readers, however I have been looking at this hand.cs for better half of 4 days with no progress.
Any and all help regarding the "public void DisplayHand(bool shortFormat, bool displaySuit)"
would be greatly appreciated, if it is not too much trouble with your answer can you outline the code to complete the return and give some feedback as to how it works.
Upvotes: 0
Views: 500
Reputation: 38456
In your Hand
class, you're storing the current hand's cards in a List<string>
suitably named cards
. In your DisplayHand
method you can iterate through the list with a foreach
loop:
foreach (Card card in cards) {
// process and/or display current card
}
Now, in your Card
class, the ToString()
method has been overloaded to accept two parameters:
public string ToString(bool shortFormat, bool displaySuit)
These same-two parameters are being conveniently passed to your DisplayHand
function in the Cards
class. Since you want to call the ToString()
method from the DisplayHand
method, you can simply pass in the arguments you received you'll be returned a nice & formatted string representing the card! You should, without much work, be able to combine the loop above with a call to the card's ToString()
to get your required output:
public void DisplayHand(bool shortFormat, bool displaySuit) {
StringBuilder cardOutput = new StringBuilder();
foreach (Card card in cards) {
if (cardOutput.Length > 0) {
// we already have one or more cards to display for this hand; separate them
// with a space-delimiter
cardOutput.Append(" ");
}
// add the current card to the display
cardOutput.Append(card.ToString(shortFormat, displaySuit));
}
Console.WriteLine(cardOutput.ToString());
}
I'm using a single space as the delimiter between cards; you can update that to whatever you see fit. Also, if you don't want each list of cards to appear on a newline, just change the Console.WriteLine()
to Console.Write()
instead.
* Note: I chose to use StringBuilder
in my example instead of basic string-concatenation for two reasons. The first is because in C#, strings are immutable (and concatenating them is far-less efficient than using StringBuilder
); the second is to show you how to use StringBuilder
(I only assume you don't use it as none of your sample code includes it). To do it without StringBuilder
(with comments/etc removed):
string cardOutput = string.Empty;
foreach (Card card in cards) {
if (!cardOutput.Equals(string.Empty)) cardOutput += " ";
cardOutput += card.ToString(shortFormat, displaySuit);
}
Console.WriteLine(cardOutput);
Upvotes: 1