gpt4 book ai didi

C# 错误 : Use of unassigned local variable

转载 作者:太空狗 更新时间:2023-10-29 21:22:30 27 4
gpt4 key购买 nike

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

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

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

其余代码供引用:*编辑:添加了一行代码

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# 错误 : Use of unassigned local variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22813697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com