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

C#程序中如何判断用户输入内容是否与指定字符串相等

问题修复方案

你注释块里的命令判断逻辑有三个硬伤:

  • C#里=是赋值操作,判断相等必须用==
  • enteredCommand是字符串类型,直接和整数1做比较类型不匹配,编译阶段就会报错
  • 读取命令、判断命令的代码全被你注释掉了,运行时根本不会执行这部分逻辑

修复后完整可运行代码

namespace Game
{
    public static class Program
    {
        public static string name;
        public static string enteredCommand;
        public static int commanddomath = 1;
        static void Main()
        {
            Console.Title = "Phil";
            Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine("                           ");
            Console.WriteLine("             / /        / /");
            Console.WriteLine("             |@|        |@|");
            Console.WriteLine("                --_____--  ");
            Console.WriteLine("                 //////    ");
            Console.WriteLine("                           ");
            

            Console.WriteLine("Hello, my name is Phil");

            Console.WriteLine("What is your name");

            name = Console.ReadLine();
            Console.WriteLine("Hello, " + name);
            
            Console.WriteLine("What do you want me to do?");
            enteredCommand = Console.ReadLine();

            // 匹配指定字符串,这里示例匹配输入"1"或者"math"触发计算逻辑
            if (enteredCommand.Trim() == "1" || enteredCommand.Trim().ToLower() == "math")
            {
                Console.WriteLine("已触发数学计算指令");
                // 在这里写commanddomath对应的业务逻辑即可
            }
            // 可按需扩展其他指令匹配分支
            else if (enteredCommand.Trim().ToLower() == "exit")
            {
                Console.WriteLine("程序退出");
                return;
            }
            else
            {
                Console.WriteLine("无法识别输入的指令");
            }

            Console.ReadKey();
        }
    }
}

使用提示

  • 匹配前加Trim()是为了自动忽略用户输入首尾不小心带的空格,加ToLower()是忽略输入大小写,避免用户输入" 1 "、"MATH"这类内容时匹配失败
  • 如果需要严格完全匹配(包括大小写、空格),直接写if (enteredCommand == "你指定的目标字符串")即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 22:03:29