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

C#练习:如何退出do-while循环?密码猜解程序循环无法终止

密码猜解程序的循环退出问题修复

你的代码有两个关键问题导致循环无法正常退出,同时错误提示也不符合需求:

  • 循环条件逻辑错误:原循环用了||(逻辑或),意思是“只要尝试次数没到3次,或者密码没输对,就继续循环”。哪怕次数到了3次,只要密码没对,!isPasswordCorrect还是true,循环就会一直跑。正确的逻辑应该是同时满足尝试次数未达上限,且密码未正确,要用&&(逻辑与)。
  • 错误提示时机错误:现在每次输错密码就会弹出“访问被拒绝”的提示,这显然不对——只有当3次机会用完之后才应该显示这个提示。

修复后的完整代码:

static void Main(string[] args)
{
    //password guesser
    string correctPassword = "kittens";
    bool isPasswordCorrect = false;
    int maxAttempts = 3;
    int attempts = 0;
    
    do
    {
        Console.WriteLine("Please enter your password: ");
        string userPassword = Console.ReadLine();

        if (userPassword == correctPassword) 
        {
            isPasswordCorrect = true;
            Console.WriteLine("You have entered the correct password!");
        }
        else
        {
            Console.WriteLine("Incorrect password! Please try again.");
            Console.WriteLine("Hint: the best fluffy animals");
            attempts++;
            
            // 只有当次数用完且密码仍错误时才提示拒绝访问
            if (attempts >= maxAttempts)
            {
                Console.WriteLine("beep boop! Too many tries, access denied!");
            }
        }
    } 
    // 循环继续的条件:还没到最大次数,且密码没对
    while (attempts < maxAttempts && !isPasswordCorrect);
}

关键改动说明:

  1. 循环条件替换为attempts < maxAttempts && !isPasswordCorrect,当尝试次数达上限或密码输入正确时,循环都会终止。
  2. 将“访问被拒绝”的提示移至else分支内,并增加attempts >= maxAttempts的判断,确保仅在3次机会耗尽后触发该提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:22:06