写C#程序的一个问题:字符串分隔符包含5个数字

a problem in writing a C# program : String separator contains 5 numbers

我想编写 C# 程序接收一个由 5 个数字组成的字符串,用逗号分隔。将它们分开并打印出来,如果字符串小于 5 或​​为空,则写上“未授权列表”,并在列表末尾打印 3 个较小的数字。 已经写好了,需要您的帮助才能完成!

Console.WriteLine("Enter a list of 5 numbers (seperated by ,): ");

string input = Console.ReadLine();

string errorMessage = "Invalid List. Try Again: ";

bool loopContinue = true;

while (loopContinue == true)
{
    string[] list = input.Split(',');
    if (input == " " || list.Count() < 5)
    {
        Console.Write(errorMessage);
        input = Console.ReadLine();
    }
    else
    {
        loopContinue = false;
        Console.WriteLine();

        for (var i = 0; i < list.Length; i++)
        {
            int.Parse(list[i]);
        }

        foreach (var x in list)
        {
            Console.WriteLine(x);
        }

        Array.Sort(list);

        Console.WriteLine("Three smallest numbers: ");
        for (var i = 0; i < 3; i++)
        {
            Console.WriteLine(list[i]);
        }
    }
}

我会使用 TryParse 而不是 Parse 来确保用户输入的是数字。

像这样:

int[] numbers = new int[list.Length];
for (var i = 0; i < list.Length; i++)
{
     bool success = int.TryParse(list[i], out numbers[i]);
     if(!success) 
     {
        Console.Write(errorMessage);
        break;
     }
}

我是这样写的,使用 Array.ConvertAll():

int[] list = null;

string errorMessage = "Invalid List. Try Again: ";
bool valid = false;
while (!valid)
{
    Console.WriteLine("Enter a list of 5 numbers (seperated by ,): ");
    string[] input = Console.ReadLine().Split(',');
    try
    {
        list = Array.ConvertAll(input, x => int.Parse(x));
        if (list.Length == 5)
        {
            valid = true;
        }                    
    } catch(Exception ex) {}
    if (!valid)
    {
        Console.WriteLine(errorMessage);
    }
}

// Sort list
Array.Sort(list);

// Print 3 smallest 
Console.WriteLine("Three smallest numbers: ");
for (var i = 0; i < 3; i++)
{
    Console.WriteLine(list[i]);
}