C# 错误:使用未赋值的局部变量



错误是在 for 循环中引起的:

for (i = 0; i < hand.Length; i++)
{
   Console.WriteLine(hand[i]);
}

我正在尝试存储这些值,以便以后能够显示它们。写行可以帮助我确保代码实际按照我的预期工作。

其余

代码供参考:*编辑:添加了一行代码

enum house //variable type for the card type
{
    Spades, Hearts, Clubs, Diamonds
}
enum cards //variable type for the cards
{
    Joker, Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King
}
class Program
{
    static void Main(string[] args)
    {
        Random rnd;
        Random rnd2;
        int i;
        int random;
        int random2;
        String[] hand;
        house randomhouse;
        cards randomcard;
        //all declared variables
        Console.WriteLine("Your hand is made up of :");
        for (i = 0; i <= 6; i++)//does everything in the {} until i is equal to 6
        {
            rnd2 = new Random();
            random2 = rnd2.Next(0, 14);
            randomcard = (cards)random2; //selecting a random card from joker to king
            if (randomcard > (int)cards.Joker) //if the random card isn't a joker
            {
                rnd = new Random();
                random = rnd.Next(0, 4);
                randomhouse = (house)random;//selects a random card type
                Console.WriteLine(randomcard + " of " + randomhouse); //outputs the name of the card
                System.Threading.Thread.Sleep(1000);//wait 1 second before getting the new card
            }
            else
            {
                Console.WriteLine(randomcard);//outputs "Joker"
                System.Threading.Thread.Sleep(1000);//wait 1 second before getting the new card
            }
            hand = new String[i];//making a new array value for every loop
            hand[i] = randomcard.ToString();//adding randomcard to the array*
        } 
        Console.Clear();
        for (i = 0; i < hand.Length; i++)
        {
            Console.WriteLine(hand[i]);
        }
        Console.ReadKey();
    }
}

编译器永远无法确定hand是否实际初始化。您应该更早地初始化它,或者将其设置为 null ,以便绕过此编译器检查。

所以你可以这样做,但这实际上是不好的做法!更改代码时,最终可能会得到NullReferenceException

String[] hand = null;

您确实知道您的代码实际上不起作用,因为最终您会得到一个数组。我想你的意思是:

hand = new String[6];
...
hand[i] = theValue;

c# 中的数组不是动态的。您需要手动调整它们的大小以在其中添加任何内容。在 for 循环之外初始化您的手。由于起手牌是 6 张大牌,您可以分配它。

string[] hand = new string[6];

如果添加了新卡,您可以使用:

Array.Resize(ref hand, (i + 1));

相关内容

  • 没有找到相关文章

最新更新