如何解决C#循环中Console.ReadLine()多次触发的问题?
问题分析与解决
你的问题核心是多次调用Console.ReadLine()却未保存输入值:
- 当输入"No"或其他内容时,第一个
if(Console.ReadLine() == "Yes")会读取你的输入,发现不匹配后,else if分支又会调用一次Console.ReadLine(),迫使你再输入一次才会触发判断,所以出现了重复输入的情况。
修正后的代码
namespace Playground { internal class Program { static void Main(string[] args) { Console.WriteLine("If you enter a number, I'll report back the number squared. Would you like to play? Enter Yes or No"); string userInput; while (true) // 简化循环条件,无需额外变量x { userInput = Console.ReadLine(); // 仅读取一次输入,存入变量复用 if (userInput == "Yes") { Console.WriteLine("Great! Enter a number"); // 新增输入验证,避免非数字导致程序崩溃 if (int.TryParse(Console.ReadLine(), out int initial)) { Console.WriteLine(initial * initial); } else { Console.WriteLine("That's not a valid number!"); } Console.WriteLine("Would you like to try again?"); } else if(userInput == "No") { Console.WriteLine("Ok, goodbye! Press any key to Exit"); Console.ReadLine(); Environment.Exit(0); } else { Console.WriteLine("Sorry, I didn't understand that. Please enter Yes or No"); } } } }
关键修改说明
- 新增
userInput变量,每次循环只读取一次用户输入,所有判断逻辑复用该变量值,彻底解决重复读取输入的问题。 - 将循环条件改为
while(true),移除无意义的变量x,简化代码逻辑。 - 添加
int.TryParse验证用户输入的数字,避免输入非数字内容时程序直接崩溃(新手开发常忽略的细节)。
内容的提问来源于stack exchange,提问作者GJardine
相关产品推荐
相关产品推荐

