C#错误:使用未分配的局部变量
该错误是由for循环引起的:C#错误:使用未分配的局部变量,c#,arrays,loops,unassigned-variable,C#,Arrays,Loops,Unassigned Variable,该错误是由for循环引起的: for (i = 0; i < hand.Length; i++) { Console.WriteLine(hand[i]); } for(i=0;i
for (i = 0; i < hand.Length; i++)
{
Console.WriteLine(hand[i]);
}
for(i=0;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();
}
}
enum house//卡类型的变量类型
{
黑桃、红桃、梅花、钻石
}
枚举卡//卡的变量类型
{
小丑,王牌,二,三,四,五,六,七,八,九,十,杰克,皇后,金
}
班级计划
{
静态void Main(字符串[]参数)
{
随机rnd;
随机rnd2;
int i;
int随机;
int-2;
弦[]手;
房子和房子;
卡片和卡片;
//所有声明的变量
控制台。WriteLine(“你的手是由:”);
对于(i=0;i(int)卡。小丑)//如果随机卡不是小丑
{
rnd=新随机数();
random=rnd.Next(0,4);
randomhouse=(house)random;//选择随机卡类型
Console.WriteLine(randomcard+“of”+randomhouse);//输出卡的名称
System.Threading.Thread.Sleep(1000);//在获得新卡之前等待1秒
}
其他的
{
Console.WriteLine(随机卡);//输出“小丑”
System.Threading.Thread.Sleep(1000);//在获得新卡之前等待1秒
}
hand=new String[i];//为每个循环生成一个新的数组值
hand[i]=randomcard.ToString();//将randomcard添加到数组中*
}
Console.Clear();
对于(i=0;i
编译器永远无法确定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));
可能是吧?真的不清楚应该有什么顺便说一句,每次通过循环时,code>都会完全覆盖数组(即,它创建一个长度为0的数组,然后用长度为1的数组替换它,以此类推)。我不确定您试图在数组中放入什么,但实际上,您可以在
for
循环后拉出该行,以获得相同的结果(并消除错误)。作为补充说明,您总是在第一个for循环中创建一个新的字符串数组,并且实际上没有在这个新数组中存储任何内容。如果要存储实际值,则必须使用hand[i]=value;