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); }
关键改动说明:
- 循环条件替换为
attempts < maxAttempts && !isPasswordCorrect,当尝试次数达上限或密码输入正确时,循环都会终止。 - 将“访问被拒绝”的提示移至else分支内,并增加
attempts >= maxAttempts的判断,确保仅在3次机会耗尽后触发该提示。
内容的提问来源于stack exchange,提问作者karo
相关产品推荐
相关产品推荐

