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

运行C# while循环无输出,视频可用代码本地无法运行求助

问题原因及修复方案

你的代码存在两个关键问题,导致程序无输出:

  1. while循环末尾的多余分号
    你在while (enteredText.Equals(""));的末尾加了分号,这会让while的循环体变成空语句,后面大括号里的代码永远不会执行。由于初始enteredText是空字符串,while条件始终为真,程序会卡在这个死循环里,自然看不到任何输出内容。

  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:16:02