String.Equals不生效:C#问答控制台程序答案判断始终错误的问题
问题成因与修复方案
核心问题所在
你代码里的System.Console.ReadKey();是导致所有答案都被判错的罪魁祸首!
当你打印完问题后调用ReadKey(),它会等待用户按下任意键(包括回车键)。当用户按回车继续时,这个回车键的输入已经被ReadKey()消耗掉了,紧接着的Console.ReadLine()就只能读到一个空字符串。这就导致不管用户之后输入什么正确答案,Answer变量都是空的,用Equals和正确答案比对自然永远不匹配,程序就一直判定错误。
修复步骤
1. 移除多余的ReadKey()
直接删掉这行代码,让Console.ReadLine()正常接收用户的输入:
static void Main(string[] args) { //Random number generator Random rnd = new Random(); int randInt = rnd.Next(0, 9); //Questions array Question/Answer string[,] array2D = new string[10, 2] { { "Mario Kart is a video game series publish by which company?", "Nintendo" }, { "What was the first console video game that allowed the game to be saved?", "The Legend of Zelda" }, { "The Connecticut Leather Company later became what toy company that was popular in the 1980s for its Cabbage Patch Kids and video game consoles?", "Coleco" }, { "Nintendo is a consumer electronics and video game company founded in what country?", "Japan" }, { "The first person shooter video game Doom was first released in what year?", "1993" }, { "In what year did Nintendo release its first game console in North America?", "1985" }, { "In the world of video games, what does NES stand for?", "Nintendo Entertainment System" }, { "In what year was the Nintendo 64 officially released?", "1996" }, { "What was the most popular video game in the year 1999?", "Doom" }, { "If you have any kind of console known to mankind, what will your mother call it no matter what?", "A Nintendo" } }; //printing the question System.Console.WriteLine(array2D[randInt, 0]); // 移除这行多余的 ReadKey() // System.Console.ReadKey(); //taking user input string Answer = Console.ReadLine(); //checking to see if the answer is correct if (Answer.Equals(array2D[randInt, 1])) { //the console exclamation for the right answer given in any scenario. Console.WriteLine("Correct Answer! Good job!"); Console.ReadKey(); } else { //the console exlamation for the incorrect answer in any given scnario Console.WriteLine("Aw man! You got it wrong! Better luck next time :("); Console.WriteLine("The correct answer was {0}", array2D[randInt, 1]); Console.ReadKey(); } }
2. 可选优化:忽略大小写比对
默认的String.Equals是区分大小写的,用户输入nintendo就会被判定错误。可以修改比对逻辑,让程序更友好:
if (string.Equals(Answer, array2D[randInt, 1], StringComparison.OrdinalIgnoreCase))
这样不管用户输入大写、小写还是混合大小写,只要内容正确就能判定为答对。
额外提示
如果确实想保留“看完问题按任意键再输入答案”的逻辑,可以这样处理:
System.Console.WriteLine(array2D[randInt, 0]); System.Console.WriteLine("Press any key to enter your answer..."); System.Console.ReadKey(true); // 添加true参数,不显示按下的键 string Answer = Console.ReadLine();
ReadKey(true)不会把用户按下的键显示在控制台,之后ReadLine()就能正常接收输入了。
内容的提问来源于stack exchange,提问作者Nesox
相关产品推荐
相关产品推荐

