为扑克牌分配号码

时间:2016-04-27 19:32:56

标签: c# loops

我正在使用C#教程进行练习,我需要从52张牌的标准牌中打印每张牌。 我有这段代码:

for (int n = 2; n <= 14; n++)
{
    for (int c = 1; c <= 4; c++)
        Console.Write(n + " " + c + " ");
}
Console.ReadKey();

但我被困住了,不知道如何用代表他们的西装和等级代替数字。 我应该使用循环和切换语句。

3 个答案:

答案 0 :(得分:4)

你可以为套装声明两个枚举,为行列声明一个枚举,然后循环遍历它们。

public enum Suits { Hearts, Spades, Clubs, Diamonds }

public enum Ranks 
{ 
    Ace, 
    Two, 
    Three, 
    Four, 
    Five, 
    Six, 
    Seven, 
    Eight, 
    Nine, 
    Ten,  
    Jack, 
    Queen, 
    King 
}

答案 1 :(得分:3)

您可以创建两个字符串数组,而只需foreach

var suites = new [] { "Clubs", "Spades", "Hearts", "Diamonds" };
var ranks = new [] { "Deuce", "Three",...., "Ace"}

foreach(var suite in suites)
    foreach(var rank in ranks)
        Console.WriteLine(rank + " of " + suite);

答案 2 :(得分:1)

使用循环和switch语句。您可以为更好的卡片和套装名称做出变化。

for (int n = 2; n <= 14; n++)
{
    for (int c = 1; c <= 4; c++)
    {
        switch (n)
        {
            case 11:
                Console.Write("J" + " ");
                break;
            case 12:
                Console.Write("Q" + " ");
                break;
            case 13:
                Console.Write("K" + " ");
                break;
            case 14:
                Console.Write("A" + " ");
                break;
            default:
                Console.Write(n.ToString() + " ");
                break;
        }
        switch (c)
        {
            case 1:
                Console.WriteLine("H");
                break;
            case 2:
                Console.WriteLine("D");
                break;
            case 3:
                Console.WriteLine("S");
                break;
            case 4:
                Console.WriteLine("C");
                break;
            default:
                Console.WriteLine("?");
                break;
        }

    }

}
Console.ReadKey();