You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决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");
            }
        }
        
    }
}

关键修改说明

  1. 新增userInput变量,每次循环只读取一次用户输入,所有判断逻辑复用该变量值,彻底解决重复读取输入的问题。
  2. 将循环条件改为while(true),移除无意义的变量x,简化代码逻辑。
  3. 添加int.TryParse验证用户输入的数字,避免输入非数字内容时程序直接崩溃(新手开发常忽略的细节)。

内容的提问来源于stack exchange,提问作者GJardine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 05:10:22