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

C#实现输入校验:非数字输入时重复询问用户

解决方案

核心思路是用TryParse方法替代Convert类的转换方法,结合循环实现输入验证,直到用户输入合法内容为止。同时封装通用的输入验证方法,避免重复代码。

修改后的完整代码:

using System;

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("---welcome to split my bill---");
        
        // 获取合法的账单总额(浮点数)
        float bill_total = GetValidFloatInput("What is the total bill?: £");
        // 获取合法的人数(整数)
        int people = GetValidIntegerInput("How many people are sharing?:");
        // 获取合法的小费比例(浮点数)
        float tip_percentage = GetValidFloatInput("What percentage tip would you like to leave?:");

        float percentage_decimal = tip_percentage / 100;
        float tip_total = bill_total * percentage_decimal;
        bill_total += tip_total;

        float costPerPerson = bill_total / people;

        Console.WriteLine($"Total Bill including tip is: £{bill_total:F2}");
        Console.WriteLine($"Total cost per person is: £{costPerPerson:F2}");
    }

    // 通用方法:获取合法的整数输入
    private static int GetValidIntegerInput(string prompt)
    {
        int inputValue;
        do
        {
            Console.Write(prompt);
            // 尝试解析输入,成功且为正整数则返回,失败提示重新输入
            if (int.TryParse(Console.ReadLine(), out inputValue) && inputValue > 0)
            {
                return inputValue;
            }
            Console.WriteLine("Invalid input! Please enter a positive whole number.");
        } while (true);
    }

    // 通用方法:获取合法的浮点数输入
    private static float GetValidFloatInput(string prompt)
    {
        float inputValue;
        do
        {
            Console.Write(prompt);
            // 尝试解析输入,成功且为非负数则返回,失败提示重新输入
            if (float.TryParse(Console.ReadLine(), out inputValue) && inputValue >= 0)
            {
                return inputValue;
            }
            Console.WriteLine("Invalid input! Please enter a valid non-negative number.");
        } while (true);
    }
}

关键说明:

  • TryParse方法:相比Convert类,它不会在输入非法时抛出异常,而是通过返回布尔值告知解析是否成功,同时通过out参数输出解析后的数值。
  • 循环验证:用do-while循环确保用户必须输入合法内容才能继续程序,避免跳过输入或输入无效值导致程序崩溃。
  • 通用方法封装:把整数和浮点数的输入验证逻辑分别封装成方法,三个输入项直接调用即可,减少代码冗余。
  • 额外校验:添加了inputValue > 0(人数)和inputValue >=0(账单、小费)的判断,符合实际业务逻辑(人数不能为0或负数,账单和小费不能为负数)。
  • 格式化输出:用字符串插值$"..."和F2格式符,确保金额显示两位小数,更符合账单场景的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:50:26