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

使用逻辑运算符的While循环陷入死循环问题求助

问题原因与修复方案

你的代码陷入无限循环的核心问题是while循环的逻辑条件错误:

你使用了||(逻辑或)运算符,这个条件的意思是「只要输入不等于Y,或者不等于N,就继续循环」。但实际上,任何字符串都不可能同时等于Y和N——输入Y时,它不等于N,条件成立;输入N时,它不等于Y,条件也成立。所以无论输入什么,循环都会一直执行。

修复后的代码

把||替换为&&(逻辑与),表示「当输入既不是Y也不是N时,才进入循环提示重新输入」:

Console.WriteLine("Connect to the Database? Y/N");
string answer = Console.ReadLine().ToUpper();
while (answer != "Y" && answer != "N")
{
    Console.WriteLine("Incorrect Response.");
    Console.WriteLine("Connect to the Database? Y/N");
    answer = Console.ReadLine().ToUpper();
}
if (answer == "N") Environment.Exit(0);

Console.WriteLine("Successful connection!");

可选优化方案

如果后续可能需要扩展更多有效输入,可以用集合来判断,可读性更强:

var validResponses = new HashSet<string> { "Y", "N" };
Console.WriteLine("Connect to the Database? Y/N");
string answer = Console.ReadLine().ToUpper();
while (!validResponses.Contains(answer))
{
    Console.WriteLine("Incorrect Response.");
    Console.WriteLine("Connect to the Database? Y/N");
    answer = Console.ReadLine().ToUpper();
}
if (answer == "N") Environment.Exit(0);

Console.WriteLine("Successful connection!");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:10:29