C#错误:使用未分配的局部变量
发布时间:2020-12-15 08:46:09 所属栏目:百科 来源:网络整理
导读:错误是在for循环中引起的: for (i = 0; i hand.Length; i++){ Console.WriteLine(hand[i]);} 我试图存储值,以便以后显示它们.写作线可以帮助我确保代码实际上按照我的意图运行. 其余代码供参考: *编辑:添加了一行代码 enum house //variable type for the
错误是在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(); } } 解决方法
编译器永远无法确定手是否已实际初始化.您应该先将其初始化,或将其设置为null,以便绕过此编译器检查.
所以你可以这样做,但事实上这是不好的做法!更改代码时,最终可能会出现NullReferenceException! String[] hand = null; 你知道你的代码实际上并不起作用,因为你最终会得到一个数组.我想你的意思是: hand = new String[6]; ... hand[i] = theValue; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby-on-rails – 从Rails中的控制台调用ApplicationContro
- PostgreSQL LIMIT子句
- xml – 什么决定了JSF版本?容器或面部配置?
- 使用vue-axios和vue-resource解决vue中调用网易云接口跨域的
- Oracle Database - Overview of Database Patch Delivery M
- C#中字符串优化String.Intern、IsInterned详解
- 正则表达式 – 使用sed忽略注释(#),但保持行不变
- cocos2d-x 实现游戏中的系统公告
- c# – 在Visual Studio 2012中使用多个非嵌套文件创建项模板
- c# – 将base64string转换为Image类型.找不到图片类型?