通过逗号分割字符串并修剪仍然在字符串中留下逗号

时间:2020-10-31 07:15:28

标签: c# string list format comma

我的任务是:编写一个程序,并要求用户提供逗号分隔的数字列表(例如5、1、9、2、10)。如果列表为空或少于5个数字,则显示“无效列表”,并要求用户重试。否则,在列表中显示3个最小的数字。

在运行代码时,出现了一个异常,说“ System.FormatException:'输入字符串的格式不正确。'”,我不确定如何将其设置为正确的格式。

这是我的代码:

while (true)
{
    Console.Write("Supply a list of comma separated numbers: ");
    string input = Console.ReadLine();
    if (string.IsNullOrWhiteSpace(input))
    {
        Console.WriteLine("The list cannot be empty or null, please try again");
    }
    else
    {
        input.Split(',');
        Convert.ToInt32(input.Trim(' '));
        var numbers = input.ToList();
        numbers.Sort();
        if (numbers.Count <= 5)
        {
            Console.WriteLine("The list has less that 5 numbers, please try again");
        }
        else
        {
            List<int> smallestThreeNumbers = new List<int>();
            for (int i = 0; i < 3; i++)
            {
                smallestThreeNumbers.Add(numbers[i]);
            }

            smallestThreeNumbers.ForEach(Console.WriteLine);
        }
    }
}

0 个答案:

没有答案