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

Visual Studio服务器停机时间计算器非浮点数输入崩溃问题求助

解决服务器停机时间计算器的输入格式崩溃问题

核心问题分析

你的代码崩溃是因为直接使用float.Parse(),当输入内容不是有效浮点数时,这个方法会直接抛出FormatException。而且你只检查了第一个输入框是否为空,既没验证它是否是有效数字,也没处理其他四个输入框的输入合法性,导致任何一个输入框的非浮点数内容都会触发崩溃。

解决方案:使用float.TryParse()做安全转换

float.TryParse()不会抛出异常,而是通过返回值告知转换是否成功,同时输出转换后的数值。我们可以遍历所有输入框,逐个验证输入有效性,只有全部输入合法时才执行计算,否则提示错误。

修改后的完整代码

public partial class Form1 : Form
{
    float[] numberInsert = new float[5];
    float sum = 0;
    float average = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void createDowntimeArray_Click(object sender, EventArgs e)
    {
        // 重置总和,避免多次点击累加
        sum = 0;
        bool allInputsValid = true;
        List<string> errorMessages = new List<string>();

        // 将所有输入框放入数组,方便遍历处理
        TextBox[] downtimeTextBoxes = new TextBox[] 
        { 
            txtDowntime1, txtDowntime2, txtDowntime3, txtDowntime4, txtDowntime5 
        };

        for (int i = 0; i < downtimeTextBoxes.Length; i++)
        {
            string input = downtimeTextBoxes[i].Text;
            // 检查输入是否为空或空白
            if (string.IsNullOrWhiteSpace(input))
            {
                errorMessages.Add($"第{i+1}个停机时间输入不能为空");
                allInputsValid = false;
                continue;
            }
            // 尝试转换为浮点数
            if (!float.TryParse(input, out float value))
            {
                errorMessages.Add($"第{i+1}个停机时间输入不是有效数字");
                allInputsValid = false;
                continue;
            }
            // 转换成功,存入数组并累加总和
            numberInsert[i] = value;
            sum += value;
        }

        if (!allInputsValid)
        {
            // 显示所有错误信息
            string errorMsg = string.Join(Environment.NewLine, errorMessages);
            MessageBox.Show(errorMsg, "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }

        // 计算平均值
        average = sum / numberInsert.Length;
        MessageBox.Show($"总停机时长: {sum.ToString()}{Environment.NewLine}平均停机时长: {average.ToString()}");
    }
}

关键改进点

  • 安全转换:用float.TryParse()替代float.Parse(),彻底避免格式异常崩溃
  • 批量处理:将所有输入框存入数组统一遍历,减少重复代码
  • 错误收集:一次性记录所有输入错误,集中提示用户,提升操作体验
  • 状态重置:每次点击按钮时重置总和,避免多次点击导致数值累加错误
  • 完整验证:同时覆盖输入为空、输入非数字两种非法场景

内容的提问来源于stack exchange,提问作者bytescript.Dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:36:03