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

C# DO-WHILE循环挑战:限制密码输入仅3次尝试

解决C# DO-WHILE循环密码尝试次数限制问题

修改后的完整代码

using static System.Console;

string? actualPassword = "ludo5656";
string? password;

int maxAttempts = 3;
int attempts = 0;

do
{
    Write("Enter your password: ");
    password = ReadLine();
    attempts++;
}
while (!string.Equals(password, actualPassword, StringComparison.Ordinal) && attempts < maxAttempts);

if (string.Equals(password, actualPassword, StringComparison.Ordinal))
{
    WriteLine("Correct!");
}
else
{
    WriteLine("Error: You've exceeded the maximum number of attempts.");
}

关键改动说明

  • 添加attempts计数器变量,用于追踪用户的尝试次数,初始值设为0
  • 每次用户输入密码后,递增attempts以统计当前尝试次数
  • 更新循环终止条件:仅当密码验证失败且尝试次数未达到上限时,才继续循环
  • 循环结束后通过判断密码是否匹配,分别输出成功提示或次数超限的错误信息
  • 使用string.Equals并指定StringComparison.Ordinal,可以更安全地处理null输入(比如用户直接回车的情况),同时保持密码验证的精确性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 17:22:26