C# User input validation, if user enters Q at any console.ReadLine it will quit the program and i can't see why its not working

using System;

namespace SummerWorkTask1
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName;
            string surname;
            string dateOfBirth;

            do
            {
                Console.WriteLine("Please enter your frist name and if at anytime you want to quit enter Q\n");
                firstName = Console.ReadLine().ToUpper();
                Console.WriteLine("Now enter your surname\n");
                surname = Console.ReadLine().ToUpper();
                Console.WriteLine("Lastly, enter your date of birth in the format of DD/MM/YY \n");
                dateOfBirth = Console.ReadLine().ToUpper();

                string customerID = $"{dateOfBirth.Replace("/", "")}{surname.Substring(0, 3)}{firstName.Substring(0, 1)}{firstName.Length} ";
                Console.WriteLine(customerID);
            } while (!firstName.Equals("Q") || !surname.Equals("Q") || !dateOfBirth.Equals("Q"));
        }
    }
}

>Solution :

You need to check for Q as you go. Here’s the way I would look at it if I were you.

static void Main(string[] args)
{
    string Ask(string message)
    {
        Console.WriteLine(message);
        string input = Console.ReadLine().ToUpper();
        Console.WriteLine();
        return input;
    }

    while (true)
    {
        string firstName = Ask("Please enter your first name and if at anytime you want to quit enter Q");
        if (firstName.Equals("Q"))
            break;
        else
        {
            string surname = Ask("Now enter your surname");
            if (surname.Equals("Q"))
                break;
            else
            {
                string dateOfBirth = Ask("Lastly, enter your date of birth in the format of DD/MM/YY");
                if (dateOfBirth.Equals("Q"))
                    break;
                else
                {
                    string customerID = $"{dateOfBirth.Replace("/", "")}{surname.Substring(0, 3)}{firstName.Substring(0, 1)}{firstName.Length} ";
                    Console.WriteLine(customerID);
                }
            }
        }
    }
}

I’d recommend against using the Environment.Exit(0); option as this only allows you one outcome. There will be few occasions in writing larger programs where you’ll actually want to quit like this.

Leave a Reply