C#控制台仅显示第一行内容 其余数组无法正常输出问题求助
问题原因
代码存在赋值对象错误的问题:当选中第2个数组(A2)和第3个数组(A3)时,仍然把生成的随机字母写入了第一个数组A1,对应的A2、A3数组从未被赋值,始终是默认null值,因此打印时没有任何内容输出。
修正后代码
string[] A1 = new string[15]; string[] A2 = new string[15]; string[] A3 = new string[15]; Random rastgele = new Random(); int selected_array = 0; int gamecount_for_a1 = 0; int gamecount_for_a2=0; int gamecount_for_a3=0; string which_letter_str; while (true) { int which_array = rastgele.Next(3); if (which_array == 0) { selected_array = 0;//A1 } else if (which_array == 1) { selected_array = 1;//A2 } else { selected_array = 2;//A3 } int which_letter_int= rastgele.Next(3); if (which_letter_int == 0) { which_letter_str = "D"; } else if (which_letter_int == 1) { which_letter_str = "E"; } else { which_letter_str = "U"; } if (selected_array ==0) { A1[gamecount_for_a1] = which_letter_str; Console.SetCursorPosition(gamecount_for_a1, 0); Console.Write(A1[gamecount_for_a1]); gamecount_for_a1++; } else if (selected_array == 1) { // 修复:将赋值对象改为A2 A2[gamecount_for_a2] = which_letter_str; Console.SetCursorPosition(gamecount_for_a2, 2); Console.Write(A2[gamecount_for_a2]); gamecount_for_a2++; } else { // 修复:将赋值对象改为A3 A3[gamecount_for_a3] = which_letter_str; Console.SetCursorPosition(gamecount_for_a3, 4); Console.Write(A3[gamecount_for_a3]); gamecount_for_a3++; } Console.ReadLine(); if (gamecount_for_a1 == 15 || gamecount_for_a2 == 15 || gamecount_for_a3 == 15) break; }
内容的提问来源于stack exchange,提问作者Beren Şenbay
相关产品推荐
相关产品推荐

