質問

I'm trying to print on the console standard deck of cards. So far this is my code and I'm stuck.

My question -- is there any way to use Suit enum in cardnumber foreach statement and basically to print card number/suit, card number/suit and so on. I know there are better ways to do this, but I'm curious is it possible to finish. Also any ideas how to print only 2's on one row, after that only 3s on row and so on?

Regards

using System;
using System.Linq;

class Print_a_Deck_of_52_Card   
{

public enum Suit
{
    Club = '\u2663',
    Diamond = '\u2666',
    Heart = '\u2665',
    Spades = '\u2660',
}

public enum CardNumber
{

    Two = 2,
    Three = 3,
    Four = 4,
    Five = 5,
    Six = 6,
    Seven = 7,
    Eight = 8,
    Nine = 9,
    Ten = 10,
    J = 11,
    Q = 12,
    K = 13,
    A = 14
}

static void Main()
{
    Console.OutputEncoding = System.Text.Encoding.Unicode;

    foreach (Suit val1 in Enum.GetValues(typeof(Suit)))
        foreach (CardNumber val in Enum.GetValues(typeof(CardNumber)))
        {
            for (int i = 0; i < 4; i++)
            {
                if ((int)val > 10)
                {

                    Console.WriteLine("{0}", val);
                }
                else
                {

                    Console.WriteLine("{0}", (int)val);

                }
            }

        }

}

}

役に立ちましたか?

解決

Yes, you can use the iterator variable anywhere within the body of the foreach loop even if that that loop contains another loop:

foreach (Suit val1 in Enum.GetValues(typeof(Suit)))
{
    foreach (CardNumber val in Enum.GetValues(typeof(CardNumber)))
    {
        if ((int)val > 10)
        {
            Console.WriteLine("{0} of {1}", val, val1);
        }
        else
        {
            Console.WriteLine("{0} of {1}", (int)val, val1);
        }
    }
}

Now, if you want to rewrite this so that all the 2's will be printed at together, and then the 3's, and so on, just swap the loops:

foreach (CardNumber val in Enum.GetValues(typeof(CardNumber)))
{
    foreach (Suit val1 in Enum.GetValues(typeof(Suit)))
    {
        if ((int)val > 10)
        {
            Console.WriteLine("{0} of {1}", val, val1);
        }
        else
        {
            Console.WriteLine("{0} of {1}", (int)val, val1);
        }
    }
}

And to write them in a row, you can use Write instead of inside the loop to keep each value together, then WriteLine outside the loop to separate that row from the next:

foreach (CardNumber val in Enum.GetValues(typeof(CardNumber)))
{
    foreach (Suit val1 in Enum.GetValues(typeof(Suit)))
    {
        if ((int)val > 10)
        {
            Console.Write("{0} of {1}", val, val1);
        }
        else
        {
            Console.Write("{0} of {1}", (int)val, val1);
        }
    }

    Console.WriteLine();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top