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
相关产品推荐
相关产品推荐

