调用Authentication方法时内部while循环未进入执行的问题咨询
问题核心原因
你代码里的while循环判断条件存在两个叠加的错误:
- 混淆了赋值运算符
=和相等比较运算符==:你要判断isAuthenticated是否为false时,应该用双等号==做比较,而不是单等号赋值。 - 运算符优先级问题:C#中
&&逻辑与运算符的优先级高于=赋值运算符,你写的while (isAuthenticated = false && count > 0)实际执行逻辑等同于isAuthenticated = (false && count > 0),false && 任意表达式结果恒为false,直接导致循环条件永远不成立,自然不会执行循环体。
修复方案
将while循环的条件修改为以下任意一种正确写法即可:
- 简洁写法(推荐):
while (!isAuthenticated && count > 0)
- 显式比较写法:
while (isAuthenticated == false && count > 0)
修复后完整代码
public static bool Authentication() { bool isAuthenticated = false; int count = 4; // 修复后的判断条件 while (!isAuthenticated && count > 0) { Console.WriteLine("Please insert your 4 digit PIN"); string pin = Console.ReadLine(); if (pin == "1704") { isAuthenticated = true; return isAuthenticated; } else { count--; Console.WriteLine($"Wrong PIN: {count} Input remained "); } } return isAuthenticated; }
内容的提问来源于stack exchange,提问作者Marco Stevanella
相关产品推荐
相关产品推荐

