How can I use some data validation to ensure that a letter or a certain number cannot be entered for this array?

Viewed 36

The code is shown below. I would like to make it so a number less than 0 cannot be entered.

double[] Fastest = new double[GymRunners];

for (int i = 0; i < GymRunners; i++)
{
    Console.WriteLine("Please enter the lane time for lane number {0}: ", i + 1);
    Fastest[i] = Convert.ToDouble(Console.ReadLine());          
}
1 Answers

Double.TryParse will help validate if the input is of type double. This function will assign the input to the out variable if the input is parse-able to double. the condition in do while will check that the input is positive.

So, try the following:

double[] Fastest = new double[GymRunners];

    for (int i = 0; i < GymRunners; i++)
    {
        do
        {
            Console.WriteLine("Please enter the lane time for lane number {0}: ", i + 1);
            Double.TryParse(Console.ReadLine(), out Fastest[i]);
        } while (Fastest[i] <= 0);
    }

Refer to this article for more about TryParse from Microsoft documentation

Related