Question

  private void GetNewDeck_Click(object sender, EventArgs e)
    {
       string[] suit = { "C", "D", "H", "S" };
        string[] num = { "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A" };
        for (int j = 0; j < 4; j++)
        {
            for (int i = 0; i < 13; i++)
            {
               NewDecktextBox.Text + = (suit[j] , num[i]"\n");
            }
        }

    }

I was trying to display a new deck of cards in a multiline textbox(NewDecktextBox) when I click the button GetNewDeck_Click button.Iam having error with the NewDecktextbox.Text line..

The output should be

 C2 C3 C4 C5 C6 C7 C8 C9 C10 CJ CQ CK CA
 D2 D3 D4 D5 D6 D7 D8 D9 D10 DJ DQ DK DA
 H2 H3 H4 H5 H6 H7 H8 H9 H10 HJ HQ HK HA
 S2 S3 S4 S5 S6 S7 S8 S9 S10 SJ SQ SK SA

Thanks

Was it helpful?

Solution

This will be a bit better

StringBuilder sb = new StringBuilder();
foreach (String suit in new string[] { "C", "D", "H", "S" })
{
  foreach (string value in new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A" } )
  {
    sb.Append(suit);
    sb.Append(value);
    sb.Append(" ");
  }
  sb.Append(Environment.NewLine);
}
NewDecktextBox.Text = sb.ToString()

Strings are immutable in .net. You way would build a new string for every card you added to the textbox, so basically 52 of them "C2 " then "C2 C3 " then ....

As soon as you start manipulating a string in a loop, StringBuilder is the way to go.

Another tip is to use foreach if you can, your way if you wanted to add another card e.g. Emperor (invented by me just now), you'd have to change the loop variables and your arrays.

Happy learning.

Environment.NewLine is the line end for the environent you are in, automatically copes with LF or CRLF.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top