Hi, I have just started C# and I have created a console application that ensures that the option 'Calculate and display (c)' is not executed if the student details and results have not been entered. I am unsure how to validate a non-entry.

Recommended Answers

All 2 Replies

This can be some kind of a leading way for you. There is plenty of way how to implement your issue, but one of my best and very efficient is to use while loop.
While some value (usually is a boolean) is not the contrary of the pre-set one, the loop is going on to infinity, until some goal is not reached. In your case this goal is when the user enters something (what ever you want).
You can even put some code for validating age, tel.numbers, and stuff like that - I actaully did an example for checking the integer - users age (but if you would like to know more, please start a new thread).

This is your code:

class Program
    {
        static void Main(string[] args)
        {
            bool bDataOK = false;
            string value = null;

            Console.WriteLine("Please write your name:"); 
            while (!bDataOK)
            {                
                value = Console.ReadLine();
                if (value != String.Empty)
                    bDataOK = true;       
                if(!bDataOK)
                    Console.WriteLine("You forgot to enter you name...");  
            }

            //now when the user has entered his bame, we can continue with the code:
            Console.WriteLine("Please enter your age:");
            bDataOK = false;
            while (!bDataOK)
            {                
                value = Console.ReadLine();
                if (value != String.Empty)
                {
                    //now checking for the age (if user really entered an integer:
                    bDataOK = CheckingAge(value);
                    if (bDataOK)
                        bDataOK = true;
                }
                if(!bDataOK)
                    Console.WriteLine("You forgot to enter you age...");  
            }
        }

        private static bool CheckingAge(string sAge)
        {
            int iAge = 0;
            bool bChecking = int.TryParse(sAge, out iAge);
            if (bChecking)
                return true;
            else
                return false;
        }
    }

PS: I hope this will give you some guidelines how this has to be done...
If you find any post as answered, please do it so. So others can find solutions for their similar issues easier.

best regards,
Mitja

Thankyou so much :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.