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

C# if-else编译错误求助:如何修复代码语法问题

修复你的C#编译错误

嘿,我看到你的问题啦!其实你搞错了错误原因哦——不是Console.WriteLine后的大括号引发的问题,罪魁祸首是if语句末尾多出来的那个分号😉

错误原因分析

当你在if (Number >= 1 && Number <= 10);后面加了分号,C#会把这个分号当作if语句的结束标记。也就是说,这个if条件判断完就直接结束了,后面的{ Console.WriteLine("Valid"); }变成了一个和if完全无关的独立代码块。而else必须和对应的if配对,现在找不到匹配的if,自然就触发编译错误了。

修复后的代码

只需要把if语句末尾的分号删掉就可以解决问题:

namespace Control_Flow_1
{
    class Program
    {
        static void Main(string[] args)
        {
            string UserInput;
            int Number;
            Console.WriteLine("Bitte geben sie eine Nummer von 1-10 ein");
            UserInput = Console.ReadLine();
            Number = Convert.ToInt32(UserInput);
            // 去掉了这里的分号,让if和后续代码块正确关联
            if (Number >= 1 && Number <= 10)
            {
                Console.WriteLine("Valid");
            }
            else
            {
                Console.WriteLine("Invalid");
            }
        }
    }
}

额外小建议(让程序更健壮)

当前代码用Convert.ToInt32(UserInput)时,如果用户输入的不是数字,会直接抛出异常。你可以用int.TryParse来更安全地处理输入,避免程序崩溃:

namespace Control_Flow_1
{
    class Program
    {
        static void Main(string[] args)
        {
            string UserInput;
            int Number;
            Console.WriteLine("Bitte geben sie eine Nummer von 1-10 ein");
            UserInput = Console.ReadLine();
            
            if (int.TryParse(UserInput, out Number))
            {
                if (Number >= 1 && Number <= 10)
                {
                    Console.WriteLine("Valid");
                }
                else
                {
                    Console.WriteLine("Invalid");
                }
            }
            else
            {
                Console.WriteLine("Bitte geben Sie eine gültige Zahl ein!");
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:03:25