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

C#计算器如何在Split操作时处理无效用户输入并抛出错误

解决计算器程序的无效输入异常问题

你的问题核心在于没有对用户输入做前置校验,直接执行Split和Parse操作,当输入格式不符合预期时就会抛出未处理的FormatException。下面是修改后的完整代码,已经添加了全面的输入校验逻辑,能处理你提到的两种错误场景,同时给出清晰的友好提示:

using System;
namespace Calculator1
{
    class Program
    {
        static void Main(string[] args)
        {
            double answer;
            bool Continue = true;
            Console.WriteLine("\tCalculator");
            Console.WriteLine("--------------------------\n");
            Console.WriteLine(" Math Operations: ");
            Console.WriteLine(" --------------------");
            Console.WriteLine(" Multiplication: *");
            Console.WriteLine(" Addition: +");
            Console.WriteLine(" Subtraction: -");
            Console.WriteLine(" Division: /");
            while (Continue)
            {
                Console.WriteLine("\nEnter your equation below:");
                Console.WriteLine(" For example: 5 + 5 ");
                string input = Console.ReadLine();
                string[] values = input.Split(' ');
                
                // 校验输入拆分后的格式是否符合「数字 操作符 数字」结构
                if (values.Length != 3)
                {
                    Console.WriteLine("❌ 错误:请按照「数字 操作符 数字」的格式输入(注意用空格分隔),比如 5 + 5");
                    goto ContinuePrompt;
                }
                
                // 校验第一个输入是否为有效数字
                if (!double.TryParse(values[0], out double firstNum))
                {
                    Console.WriteLine($"❌ 错误:「{values[0]}」不是有效的数字,请重新输入");
                    goto ContinuePrompt;
                }
                
                // 校验第二个输入是否为有效数字
                if (!double.TryParse(values[2], out double secondNum))
                {
                    Console.WriteLine($"❌ 错误:「{values[2]}」不是有效的数字,请重新输入");
                    goto ContinuePrompt;
                }
                
                string operation = values[1];
                // 校验操作符是否为支持的类型
                bool isValidOperation = operation == "*" || operation == "/" || operation == "+" || operation == "-";
                if (!isValidOperation)
                {
                    Console.WriteLine($"❌ 错误:「{operation}」不是支持的操作符,支持的操作符为 *、+、-、/");
                    goto ContinuePrompt;
                }
                
                // 执行计算逻辑
                switch (operation)
                {
                    case "*":
                        answer = firstNum * secondNum;
                        Console.WriteLine($"\n{firstNum} * {secondNum} = {answer}");
                        break;
                    case "/":
                        // 额外添加除数为0的校验
                        if (secondNum == 0)
                        {
                            Console.WriteLine("❌ 错误:除数不能为0,请重新输入");
                            goto ContinuePrompt;
                        }
                        answer = firstNum / secondNum;
                        Console.WriteLine($"\n{firstNum} / {secondNum} = {answer}");
                        break;
                    case "+":
                        answer = firstNum + secondNum;
                        Console.WriteLine($"\n{firstNum} + {secondNum} = {answer}");
                        break;
                    case "-":
                        answer = firstNum - secondNum;
                        Console.WriteLine($"\n{firstNum} - {secondNum} = {answer}");
                        break;
                }
                
            ContinuePrompt:
                Console.WriteLine("\n\nDo you want to continue?");
                Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
                string response = Console.ReadLine();
                Continue = response.Equals("Yes", StringComparison.OrdinalIgnoreCase); // 忽略大小写,提升体验
            }
        }
    }
}

关键修改点说明:

  • 用double.TryParse替代double.Parse:这个方法不会抛出异常,而是通过返回值告知解析是否成功,同时通过out参数拿到解析后的数字,避免了未处理的格式异常。
  • 添加数组长度校验:确保用户输入的内容拆分后正好是3个部分,处理像5*5这种无空格的错误输入。
  • 操作符合法性校验:明确检查操作符是否在支持范围内,避免非法操作符导致的逻辑错误。
  • 新增除数为0校验:补上原代码遗漏的边界场景,避免除零异常。
  • 简化流程跳转:用goto直接跳转到继续询问环节,避免嵌套过多的else逻辑,代码更易读。
  • 忽略大小写的继续判断:用户输入yes、YES都能触发继续操作,更符合日常使用习惯。

现在测试你提到的错误场景:

  1. 输入5*5:会提示“请按照「数字 操作符 数字」的格式输入(注意用空格分隔)”
  2. 输入a * b:会提示“「a」不是有效的数字,请重新输入”

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:31:21