运行C# while循环无输出,视频可用代码本地无法运行求助
问题原因及修复方案
你的代码存在两个关键问题,导致程序无输出:
while循环末尾的多余分号
你在while (enteredText.Equals(""));的末尾加了分号,这会让while的循环体变成空语句,后面大括号里的代码永远不会执行。由于初始enteredText是空字符串,while条件始终为真,程序会卡在这个死循环里,自然看不到任何输出内容。Console.Read()缺少分号
代码最后一行Console.Read()末尾没有加分号,这会直接导致编译错误。
另外,你引用了两个完全没用的命名空间:System.ComponentModel.Design和System.Threading.Channels,可以直接删除以减少冗余。
修复后的完整代码
using System; namespace IfStatements { class Program { static void Main(string[] args) { int counter = 0; string enteredText = ""; while (enteredText.Equals("")) { Console.WriteLine("请按回车键将人数加1,输入其他内容结束计数。"); enteredText = Console.ReadLine(); counter++; Console.WriteLine("当前室内人数为 {0}", counter); Console.Read(); } } } }
可选逻辑优化
如果希望用户输入非空内容时直接退出,不执行最后一次计数,可以调整判断逻辑:
using System; namespace IfStatements { class Program { static void Main(string[] args) { int counter = 0; string enteredText = ""; while (enteredText.Equals("")) { Console.WriteLine("请按回车键将人数加1,输入其他内容结束计数。"); enteredText = Console.ReadLine(); if (enteredText.Equals("")) { counter++; Console.WriteLine("当前室内人数为 {0}", counter); } Console.Read(); } } } }
内容的提问来源于stack exchange,提问作者Ayman khaled
相关产品推荐
相关产品推荐

