vendredi 25 décembre 2020

Nested If statements for checking eligbility

so I am pretty new to C# and after learning some fundamentals I tried making a simple program to check for someone's eligibility using if statements. The program asks for 3 things: Age, Height, and CollegeDegree You have to be 18 to go to the next question and you have to be taller than 160cm to go to the CollegeDegree question.

Now the program works fine, however looking at it, I come to realize that there are a lot of nested if statements and the code is just messy and unreadable.

What would I need to do to make it cleaner? I tried just doing it as follows

if
else
if
else

However, that causes the issue that if the first condition is not met, so the age is < 18 it just runs the next if statement instead of making the user be ineligible.

Current Code:

static void Main(string[] args)
        {
            int ageInput;
            int heightInput;
            bool hasCollegeDegree;
            
            
            Console.WriteLine("How old are you?");
            ageInput = Convert.ToInt32(Console.ReadLine());

            if (ageInput >= 18)
            {
                Console.WriteLine("You are older than 18");
                
                Console.WriteLine("How tall are you?");
                heightInput = Convert.ToInt32(Console.ReadLine());
                if (heightInput >= 160)
                {
                    Console.WriteLine("You are taller than 160cm");
                    
                    Console.WriteLine("Do you have a college degree?");
                    hasCollegeDegree = Convert.ToBoolean(Console.ReadLine());
                    if (hasCollegeDegree == true)
                    {
                        Console.WriteLine("You have a college degree");
                        Console.WriteLine("You are eligible");
                    }
                    else
                    {
                        Console.WriteLine("No College Degree");
                        Console.WriteLine("You are ineligible");
                    }
                }
                else
                {
                    Console.WriteLine("You are too short");
                }
            }
            else
            {
                Console.WriteLine("You are too young");
            }
        }

Aucun commentaire:

Enregistrer un commentaire